python将图片分割成两部分

问题来源:最近使用ZED拍摄图片,在使用官方SDK中的ZED Explorer时发现保存的图片是将左右眼的图像保存为左右并列的一张图片,处理时需要两张单独的图片,因此写了个简单的分割程序,以供参考。

"""
split zed camera image to left image and right image.
eg: img[0:h, 0:w, : ] --> leftimg[0:h, 0:int(w/2), : ] and rightimg[0:h, int(w/2+1):w, : ].
"""

import cv2
import os

if __name__ == "__main__":
    path = "E:\ZED\\1228"   # change this dirpath.
    listdir = os.listdir(path)
    
    newdir = os.path.join(path, 'split')    # make a new dir in dirpath.
    if(os.path.exists(newdir) == False):
        os.mkdir(newdir)
        
    for i in listdir:
        if i.split('.')[1] == "png":	# the format of zed img.
            filepath = os.path.join(path, i)
            filename = i.split('.')[0]
            leftpath = os.path.join(newdir, filename) + "_left.png"
            rightpath = os.path.join(newdir, filename) + "_right.png"

            img = cv2.imread(filepath)
            [h, w] = img.shape[:2]
            print(filepath, (h, w))
            limg = img[:, :int(w/2), :]
            rimg = img[:, int(w/2+1):, :]

            cv2.imwrite(leftpath, limg)
            cv2.imwrite(rightpath, rimg)

你可能感兴趣的:(CV)