如何从主要大盒子中分离颜色填充并使用正确的标签保存它们

问题描述 投票:0回答:1

这是主输入图像(名为1.png):

现在,我想确定哪个方框填充了颜色,哪个方框是空的,在中心大框中,而不是20个有数字的边框。

我编写代码从图像中提取主要大框:

image = cv2.imread(path)

gray = cv2.cvtColor(image , cv2.COLOR_BGR2GRAY)

edge = cv2.Canny(gray.copy() , 10 ,70)

_,contours,_ = cv2.findContours(edge.copy() , cv2.RETR_EXTERNAL ,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(image, contours , -1, (0,0,255) , 3)
plt.imshow(image)
cv2.imwrite('image.jpg',image)

现在图像看起来像这样:

然后我对轮廓进行了排序,得到了包含所有彩色和非彩色框的主矩阵框。

sorted_contours = sorted(contours,key = cv2.contourArea,reverse=True)

然后我把主箱分开了:

img = cv2.imread('1.png')
cnt = sorted_contours[0]
x,y,w,h = cv2.boundingRect(cnt)
main_box = img[y:y+h,x:x+w].copy()
cv2.imwrite('main_box.jpg',main_box)
plt.imshow(main_box)

所以,主框现在看起来像这样:

标记外部盒子

main_box_gray = cv2.cvtColor(main_box,cv2.COLOR_BGR2GRAY)
_, main_box_gray = cv2.threshold(main_box_gray,5,255,cv2.THRESH_BINARY)


_,t_c,_ = cv2.findContours(main_box_gray.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

colored_main_box = img[y:y+h,x:x+w].copy()

cv2.drawContours(colored_main_box,t_c,-1,(255,0,0),2)

外框被标记,现在我将外轮廓分开以获得内部框:

sorted_box = sorted(t_c,key = cv2.contourArea,reverse=True)

colored_main_box = img[y:y+h,x:x+w].copy()
cnt = sorted_box[0]

x2,y2,w2,h2 = cv2.boundingRect(cnt)

temp_image = colored_main_box[y2:y2+h2,x2:x2+w2].copy()


edge_temp = cv2.Canny(temp_image,100,200)

_,t_c_1,_ = cv2.findContours(edge_temp.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

colored_main_box = img[y:y+h,x:x+w].copy()

colored_main_box = colored_main_box[y2:y2+h2,x2:x2+w2].copy()

cv2.drawContours(colored_main_box,t_c_1,-1,(0,0,255),1)

plt.imshow(colored_main_box)
cv2.imwrite("full_marked.jpg",colored_main_box)

colored_main_box(全标):

现在我已经标记了所有内框,我可以使用cv2.countNonZero功能找到哪个框填充,但我的主要任务是将填充框内的颜色保存为单独的图像,而不包含包含该颜色的框的外部黑色边框填充,以及仅包含颜色填充的已保存图像应以提取它的框命名。

例如:在main_box.jpg图片中:

橙色应保存为8.jpg

红色应保存为12.jpg

绿色应保存为18.jpg

黄色应该保存为19.jpg

蓝色应该是数字21.jpg

请帮我提供代码,用正确的数字标签提取并保存包装盒内的颜色填充。

python python-3.x opencv
1个回答
0
投票

您需要解决两个问题子集。

  1. 得到彩色框的边框。
  2. 使用框索引命名它们首先我们需要裁剪与每种颜色相对应的图像。要获取Image中的颜色,请使用以下命令:
unique_col = set( tuple(v) for col in image for v in col )     
for color in unique_col:
    if col == (0,0,0) or col == (255,255,255):
       continue
    idx_set = np.where((image == col).all(axis=2))
    min_x = min(idx_set[:,0])
    min_y = min(idx_set[:,1])
    max_x = max(idx_set[:,0])
    max_y = max(idx_set[:,1]) 
    #this will give you bounding box for that particular color

步骤2:分配正确的名称让bbox_small成为主要大框中每个小框的边界框,然后根据所有矩形(= sorted_bbox数组)的一个角的y坐标对其进行排序。并将key(id)分配给sorted_bbox + 1中每个box =该框的索引

现在

for every colored box:
    name = i+1 such that colored_box lies inside sorted_box[i]

我没有写过任何代码,只是一个想法。另外我认为使用Hough Transform来获取矩形角也是一种很好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.