天天看點

【python圖像處理】單張圖像裁剪與批量圖檔裁剪一、效果二、代碼

一、效果

【python圖像處理】單張圖像裁剪與批量圖檔裁剪一、效果二、代碼
【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)