Home > Software design >  Error in cropping the image using binary mask
Error in cropping the image using binary mask

Time:10-08

I would like to crop my original image using the binary mask for which I have written code

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))

I am getting an error which states

NameError: name 'New_image' is not defined

Kindly suggest me where i am making a mistake here

CodePudding user response:

You should use the function, and maybe assign the return value to New_image variable:

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))

Or you could do this, without the New_image variable:

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

CodePudding user response:

You have only created the function crop, but you haven't called it. You will have to create the variable and assign the value you get from the function, and only then use it for the plot.

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))
  • Related