When using the COCO Format, you often want to extract only certain objects. At that time, it is necessary to use the polygon information as a mask to extract the object from the image. Even if I look for this method, I can't find it. This time I will introduce such a method.
First of all, you should be able to see it in seconds by looking at the code below.
import cv2
src_img = cv2.imread("YOUR_PATH")
# parameter
sg = [1, 1, 2, 2, 3, 3]
bb = [1, 1, 2, 2]
# working file
mask = np.zeros_like(src_img) # (y, x, c)
# segmentation data
sg = np.asarray(sg[0])
poly_number = int(len(sg)/2)
poly = np.zeros( (poly_number, 2) )
for i in range(poly_number):
poly[i][0] = sg[(i * 2) + 0] # x
poly[i][1] = sg[(i * 2) + 1] # y
# generate mask
mask = cv2.fillConvexPoly(mask, np.array(poly, 'int32'), color=(255, 255, 255))
# generate src_img and mask_image
cv2.imwrite("./src_img.png ", src_img)
cv2.imwrite("./mask.png ", mask)
# masked image
masked_src_img = np.where(mask==255, src_img, mask)
cv2.imwrite("./procData/masked.png ", masked_src_img)
# cropping img
bb = np.asarray(bb, 'int32')
offset_x = bb[0]
offset_y = bb[1]
length_x = bb[2]
length_y = bb[3]
cv2.imwrite("./masked_crop.png ", masked_src_img[offset_y : (offset_y + length_y), offset_x : (offset_x + length_x)])
First, the polygon is converted to a mask image below. It should be noted that an error other than ʻint32` will occur.
cv2.fillConvexPoly(mask, np.array(poly, 'int32'), color=(255, 255, 255))
Next, you only have to specify that the part of the mask image with the 255 value uses the value of src_img
.
masked_src_img = np.where(mask==255, src_img, mask)
Finally, if you crop in the Bounding box, you can extract a specific area.
Enjoy !
Recommended Posts