OpenCV:尝试保存补丁时 imwrite 不起作用

OpenCV: imwrite is not working when trying to save patches

我正在使用库 patchify 为形状为 (3136,4032,3) 的图像 (test.jpg) 创建形状为 (224,224,3) 的补丁,然后取消补丁以将它们放回原处。要创建我使用的补丁:

img = cv2.imread("test.jpg")
patches_img = patchify(img, (224,224,3), step=224)

创建补丁后,我想将每个补丁保存在选定的目录中,使用 cv2.imwrite:

for i in range(patches_img.shape[0]):
    for j in range(patches_img.shape[1]):
        single_patch_img = patches_img[i,j,:,:]
        if not cv2.imwrite('patches/images/' + 'image_' + str(img) + '_'+ str(i)+str(j)+'.jpg', single_patch_img):
            raise Exception("Could not write the image")   

我写过 cv2.imwrite 失败时引发异常的原因,它静默失败。 所以当我运行 cv2.imwrite时,异常发生了。这可能与我处理每个补丁的方式有关,但我很难找到问题所在。

非常欢迎任何建议,谢谢!!

我可以确定两个问题:

  • single_patch_img = patches_img[i,j,:,:]替换为:

     single_patch_img = patches_img[i, j, 0, :, :, :]
    
  • 替换cv2.imwrite('patches/images/' + 'image_' + str(img) + '_'+ str(i)+str(j)+'.jpg', single_patch_img)

     cv2.imwrite('patches/images/' + 'image_' + '_'+ str(i)+str(j)+'.jpg', single_patch_img)
    

patches_img的形状是(14, 18, 1, 224, 224, 3),patch图像的期望形状是(224, 224, 3)
结论是相关补丁索引是最后三个:patches_img[i, j, 0, :, :, :].


在命令中cv2.imwrite('patches/images/' + 'image_' + str(img) + '_'+ str(i)+str(j)+'.jpg', single_patch_img)
您正在使用:str(img)

str(img) 将 NumPy 数组 img 转换为字符串。
结果类似于 '[[[103 119 142]\n [103 119 142]\n [103 119 142]\n ...\n [ 12 26 44]\n [ 12 26 45]\n ...

这不是合法的文件名。
您可以删除 str(img) 部分或将其替换为有效字符串。


更正后的代码示例:

import cv2
from patchify import patchify

img = cv2.imread("test.jpg")
patches_img = patchify(img, (224,224,3), step=224)

for i in range(patches_img.shape[0]):
    for j in range(patches_img.shape[1]):
        single_patch_img = patches_img[i, j, 0, :, :, :]
        # if not cv2.imwrite('patches/images/' + 'image_' + '_'+ str(i)+str(j)+'.jpg', single_patch_img):
        if not cv2.imwrite('patches/images/' + 'image_' + '_'+ str(i).zfill(2) + '_' + str(j).zfill(2) + '.jpg', single_patch_img):
            raise Exception("Could not write the image")