Reputation: 303
here's my image:
i have 2 classes dog and truck i also have their bbox coordinates so i want to create a mask for this image so i applied grapcut algorithm here's my code
img=cv2.imread('dog.jpg')
mask=np.zeros(img.shape[:2],np.uint8)
bgModel=np.zeros((1,65),np.float64)
fgModel=np.zeros((1,65),np.float64)
tmpimage=image
masks=[]
for i in recs:
cv2.grabCut(img,mask,i,bgModel,fgModel,10,cv2.GC_INIT_WITH_RECT)
mask2=np.where((mask==2)|(mask==0),0,1).astype('uint8')
masks.append(mask2)
#img=image*mask2[:,:,np.newaxis]
finalmask=np.zeros(img.shape[:2],np.uint8)
for i in range(len(masks)):
finalmask=finalmask+masks[i]
plt.imshow(finalmask)
# plt.colorbar()
#plt.xticks([]),plt.yticks([])
plt.show()
here's the final mask:
what i want to do is i want the area of the dog to have different color than area of the truck in this image both are having the same yellow color
Upvotes: 0
Views: 471
Reputation: 21203
In your case finalmask
is a 2-channel image. The output you get from plt.imshow(finalmask)
is a binary image where yellow -> 255 and purple -> 0.
I have created a mask with 3-channels and assigned random colors for each mask.
Code:
# creating 3-channel mask:
finalmask = np.zeros(img.shape, np.uint8)
for i in range(len(masks)):
# generating random color
# plucked from: https://stackoverflow.com/questions/28999287/generate-random-colors-rgb
color = tuple(np.random.choice(range(256), size=3))
# create another mask to place color in white regions
im = np.zeros(img.shape, np.uint8)
im[masks[i] == 255] = color
# add with final mask
finalmask = finalmask + im
Results:
Here sample masks I created:
End result:
Note: If you want fixed color for each mask label, you can create a dictionary and refer from it.
Upvotes: 1