When segment an image with same mask multiple times continuously with same parameters, get different results.
When I grabcut an image with the same mask multiple times continuously, I got different segment results. The parameters are same too, for example the iteration was set as 1. Although the difference is very small( at pixel-level), it should be same.
But, for same image and mask, if I run the grabcut once, then restart the program run again, the results are same.
The attach is example of test image and related mask, and three results(to show clearly, I used the color-codedimage [0,0,0]==background, [255,0,0] == foreground, [0,0,255]== possible background). You can change them to mask label.
Looking forwards to your answers.
the code is as following:
import cv2
import numpy as np
imgCut = cv2.imread('test.png', 1)
maskimg = cv2.imread('testmask.png', 1)
GrayImg = cv2.cvtColor(maskimg, cv2.COLOR_BGR2GRAY)
# first grabcut & its result
mask = np.zeros(GrayImg.shape, np.uint8)
mask[GrayImg > 20] = 2
mask[GrayImg > 70] = 1
mask[GrayImg == 0] = 0
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
mask, bgdModel, fgdModel = cv2.grabCut(imgCut, mask, None, bgdModel, fgdModel, 1, cv2.GC_INIT_WITH_MASK)
newmask = np.where((mask == 2) | (mask == 0), 0, 255).astype('uint8')
imgF = imgCut * newmask[:, :, np.newaxis]
cv2.imwrite('cut.png', imgF)
# second grabcut & its result
mask1 = np.zeros(GrayImg.shape, np.uint8)
mask1[GrayImg > 20] = 2
mask1[GrayImg > 70] = 1
mask1[GrayImg == 0] = 0
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
mask1, bgdModel, fgdModel = cv2.grabCut(imgCut, mask1, None, bgdModel, fgdModel, 1, cv2.GC_INIT_WITH_MASK)
newmask1 = np.where((mask1 == 2) | (mask1 == 0), 0, 255).astype('uint8')
imgF1 = imgCut * newmask1[:, :, np.newaxis]
cv2.imwrite('cut1.png', imgF1)
# third grabcut & its result
mask2 = np.zeros(GrayImg.shape, np.uint8)
mask2[GrayImg > 20] = 2
mask2[GrayImg > 70] = 1
mask2[GrayImg == 0] = 0
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
mask2, bgdModel, fgdModel = cv2.grabCut(imgCut, mask2, None, bgdModel, fgdModel, 1, cv2.GC_INIT_WITH_MASK)
newmask2 = np.where((mask2 == 2) | (mask2 == 0), 0, 255).astype('uint8')
imgF2 = imgCut * newmask2[:, :, np.newaxis]
cv2.imwrite('cut2.png', imgF2)
have you read doc ? if you don't understand you can read paper too "GrabCut” — Interactive Foreground Extraction using Iterated Graph Cuts"
@LBerger, I know how to use grabcut also the theory. I just make an experiment. When I segment an image for three times with same parameters and mask, but the segmented results are different. I want to ask why
show your code
@LBerger the code is attached. I also ask my friends, opencv for android&ios also have the same issue.
@LBerger I test a group of 30 images, they all have the same issue. The image in this question is just an example. You can test it, thanks.