【python图像处理】单张图像裁剪与批量图片裁剪

一、效果

二、代码

1、单张图片裁剪

# 将单张图片分成5张
import cv2
import numpy as np
srcImg = cv2.imread("F:/test.jpg")
cv2.imshow("[srcImg]",srcImg)

# shap[0] height,shape[1] width
print(srcImg.shape)
hei=srcImg.shape[0]
wid=srcImg.shape[1]

# get 5 roi
num=5
for i in range(0,num):
    print(i)
    hei_0=0
    hei_1=int(hei)
    wid_0=int(i*wid/num)
    wid_1=int((i+1)*wid/num)
    roiImg = srcImg[hei_0:hei_1, wid_0:wid_1]
    # cv2.imshow("[ROIImg]", roiImg)
    path="F:/out/"+str(i)+".jpg"
    cv2.imwrite(path,roiImg)

2、批量图片裁剪

# 处理多张图片
import numpy as np
import glob as glob
import cv2
import os

# Returns a list of all folders with participant numbers
# img_path = glob.glob("F:/test/*jpg")
# for path in img_path:
#     img  = cv2.imread(path)
#     cv2.imshow('img',img)
#     cv2.waitKey(1000)

# 循环处理列表中的所有图片
path = os.path.expanduser("F:/test/")
for f in os.listdir(path):
    # print(f.strip()[0:-4])

    path="F:/test/"+f.strip()
    print(path)
    img = cv2.imread(path)
    # cv2.imshow('img', img)
    # shap[0] height,shape[1] width
    hei = img.shape[0]
    wid = img.shape[1]

    # get 5 roi
    num = 5
    for i in range(0, num):
        print(i)
        hei_0 = 0
        hei_1 = int(hei)
        wid_0 = int(i * wid / num)
        wid_1 = int((i + 1) * wid / num)
        roiImg = img[hei_0:hei_1, wid_0:wid_1]
        # cv2.imshow("[ROIImg]", roiImg)
        path = "F:/out/" +f.strip()[0:-4]+"_"+ str(i) + ".jpg"
        cv2.imwrite(path, roiImg)

 

你可能感兴趣的:(图像处理,python)