使用OpenCV和Python编写图像作物的难度

时间:2017-04-01 04:09:19

标签: python opencv image-processing

我使用以下代码从文件夹中读取多个图像并从所有文件中获取特定裁剪,并在最后编写它们。裁剪部分似乎不起作用意味着裁剪的部分没有被写入。

# import the necessary packages
import cv2
import os, os.path


#image path and valid extensions
imageDir = "C:\\Users\\Sayak\\Desktop\\Training\\eye\\1" #specify your path here
image_path_list = []
valid_image_extensions = [".jpg", ".jpeg", ".png", ".tif", ".tiff"] #specify your vald extensions here
valid_image_extensions = [item.lower() for item in valid_image_extensions]

#create a list all files in directory and
#append files with a vaild extention to image_path_list
for file in os.listdir(imageDir):
    extension = os.path.splitext(file)[1]
    if extension.lower() not in valid_image_extensions:
        continue
    image_path_list.append(os.path.join(imageDir, file))

#loop through image_path_list to open each image
for imagePath in image_path_list:
    image = cv2.imread(imagePath)

    # display the image on screen with imshow()
    # after checking that it loaded
    if image is not None:
        cv2.imshow(imagePath, image)
    elif image is None:
        print ("Error loading: " + imagePath)
        #end this loop iteration and move on to next image
        continue
    crop_img = image[200:400, 100:300]
    cv2.imwrite('pic{:>05}.jpg'.format(imagePath), crop_img)

    # wait time in milliseconds
    # this is required to show the image
    # 0 = wait indefinitely
    # exit when escape key is pressed
    key = cv2.waitKey(0)
    if key == 27: # escape
        break
# close any open windows
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

我已修改您上面发布的代码。 问题在于您在cv2.imwrite()中使用的字符串格式第一个参数必须是文件保存位置的绝对路径,但是您的代码正在传递这样的内容。 pic {:> 05} .jpg => pic / home / ubuntu / Downloads / 10_page.png.jpg。当我使用有效的文件名时,保存裁切后的图像完全没有问题。

#loop through image_path_list to open each image
for i,imagePath in enumerate(image_path_list):
    image = cv2.imread(imagePath)
    # display the image on screen with imshow()
    # after checking that it loaded
    if image is not None:
        cv2.imshow(imagePath, image)
    elif image is None:
        print ("Error loading: " + imagePath)
        #end this loop iteration and move on to next image
        continue
    # Please check if the size of original image is larger than the pixels you are trying to crop.
    (height, width, channels) = image.shape
    if height >= 400 and width >= 300:
        plt.imshow(image)
        plt.title('Original')
        plt.show()
        crop_img = image[100:400, 100:400]

        # Problem lies with this path. Ambiguous like pic/home/ubuntu/Downloads/10_page.png.jpg
        print('pic{:>05}.jpg'.format(imagePath))

        # Try a proper path. A dirname + file_name.extension as below, you will have no problem saving.
        new_image = os.path.join(imageDir,'{}.png'.format(str(i)))
        cv2.imwrite(new_image, crop_img)
        plt.imshow(crop_img)
        plt.title('Cropped')
        plt.show()