使用二进制蒙版裁剪图像时出错

Error in cropping the image using binary mask

我想使用我为其编写代码的二进制掩码裁剪原始图像

import cv2
import numpy as np
import matplotlib as plt

img = cv2.imread("image.png")
mask = cv2.imread("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))
 New_image = cv2.bitwise_or(fg, fg_back_inv)
 return New_image

plt.imshow(cv2.cvtColor(New_image, cv2.COLOR_BGR2RGB))

我收到一条错误消息

NameError: name 'New_image' is not defined

请指教我这里哪里出错了

您应该使用该函数,并且可以将 return 值分配给 New_image 变量:

import cv2
import numpy as np
import matplotlib as plt

img = cv2.imread("image.png")
mask = cv2.imread("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))
 New_image = cv2.bitwise_or(fg, fg_back_inv)
 return New_image

New_image = crop(img,bg,mask)        #   <--------------
plt.imshow(cv2.cvtColor(New_image, cv2.COLOR_BGR2RGB))

或者你可以这样做,没有 New_image 变量:

plt.imshow(cv2.cvtColor(crop(img,bg,mask), cv2.COLOR_BGR2RGB)

您只创建了函数crop,但还没有调用它。您将必须创建变量并分配从函数中获得的值,然后才将其用于绘图。

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))
 New_image = cv2.bitwise_or(fg, fg_back_inv)
 return New_image
New_image = crop(img, bg, mask)
plt.imshow(cv2.cvtColor(New_image, cv2.COLOR_BGR2RGB))