在python中基于自定义掩码裁剪图像时出错

在python中基于自定义掩码裁剪图像时出错,python,image,opencv,computer-vision,cv2,Python,Image,Opencv,Computer Vision,Cv2,我有两张照片: 我想用第一个的白色形状来裁剪图像,如下所示: 没有蓝线和信息 这就是我想做的: def find_intersection(self, mask, image): image = cv2.cvtColor(np.float32(image), cv2.COLOR_BGR2GRAY) masked = cv2.bitwise_and(mask, image, mask=mask) plt.imshow(masked)

我有两张照片:

我想用第一个的白色形状来裁剪图像,如下所示:

没有蓝线和信息

这就是我想做的:

 def find_intersection(self, mask, image):
        image = cv2.cvtColor(np.float32(image), cv2.COLOR_BGR2GRAY)
        masked = cv2.bitwise_and(mask, image, mask=mask)
        plt.imshow(masked)
        plt.show()
但我得到了这个错误:

cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-kh7iq4w7\opencv\modules\core\src\arithm.cpp:234: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function 'cv::binary_op'

图片的尺寸和通道是相同的,所以我不知道问题出在哪里。

您的代码中有两个缺陷:

  • 您呈现的两幅图像大小不同<代码>(8591215,3)和
    (8571211,3)

  • cv2.bitwise_和
    方法的掩码关键字参数必须是二进制图像,这意味着它只能有一个通道

  • 您可以使用该方法修复大小差异,并且可以使用该方法和
    cv2.COLOR\u bgr2 gray
    选项将遮罩的通道转换为1(或者在读取遮罩文件后,可以在图像文件的名称后传入
    0

    我会这样做:

    import cv2
    import numpy as np
    
    img = cv2.imread("ring_bg.png")
    mask = cv2.imread("ring_mask.png")
    
    h, w, _ = img.shape
    mask = cv2.resize(cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY), (w, h)) # Resize image
    bg = np.zeros_like(img, 'uint8') # Black background
    
    def crop(img, bg, mask):
        fg = cv2.bitwise_or(img, img, mask=mask)            
        fg_back_inv = cv2.bitwise_or(bg, bg, mask=cv2.bitwise_not(mask))
        return cv2.bitwise_or(fg, fg_back_inv)
    
    cv2.imshow("Image", crop(img, bg, mask))
    cv2.waitKey(0)
    
    输出: