I perform the segmentation of a video frame using grabcut algorithm. I save the foreground image as png file. But when I try to read that image the pixel values of that foreground image will be zero. Why is it so?
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread(‘frame38.png’)
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (270,100,450,600)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
values=(
(“Definite Background”, cv2.GC_BGD),
(“Probable Background”, cv2.GC_PR_BGD),
(“Definite Foreground”, cv2.GC_FGD),
(“Probable Foreground”, cv2.GC_PR_FGD),
)
loop over the possible GrabCut mask values
for (name, value) in values:
# construct a mask that for the current value
print(“[INFO] showing mask for ‘{}’”.format(name))
valueMask = (mask == value).astype(“uint8”) * 255
# display the mask so we can visualize it
cv2.imshow(name, valueMask)
cv2.waitKey(0)
outputMask = np.where((mask == cv2.GC_BGD) | (mask == cv2.GC_PR_BGD),0, 1)
outputMask=(outputMask*255).astype(“uint8”)
output=cv2.bitwise_and(img, img, mask=outputMask)
show the input image followed by the mask and output generated by
GrabCut and bitwise masking
#cv2.imshow(“Input”, img)
#cv2.imshow(“GrabCut Mask”, outputMask)
cv2.imshow(“GrabCut Output”, output)
cv2.imwrite(“select_image2.png”,output)
#cv2.waitKey(0)
plt.subplot(121), plt.imshow(img)
plt.title(“grabcut”), plt.xticks(), plt.yticks()
plt.subplot(122),
plt.imshow(cv2.cvtColor(cv2.imread('frame38.png"),
cv2.COLOR_BGR2RGB))
plt.title(“original”), plt.xticks(), plt.yticks()
plt.show()