我有这张带标签的图像,我想用包围盒将每种颜色包围起来以找到每个物体的中心 我该如何使用python或javascript的Open Cv库做到这一点
connected component labeled image
我是python的初学者,我尝试过此代码,但显示错误: 服务器遇到内部错误,无法完成您的请求。
错误消息: 标头之前的脚本输出结束:bounding_color_objects.py
#!c:\Users\Asus\AppData\Local\Programs\Python\Python37-32\python.exe
import cgitb
cgitb.enable()
print('Content-type: text/html\r\n')
print('\r\n')
import cv2
import numpy as np
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h,_,_ = cv2.split(image_hsv)
bins = np.bincount(h.flatten())
MIN_PIXEL_CNT_PCT = (1.0/20.0)
peaks = np.where(bins > (h.size * MIN_PIXEL_CNT_PCT))[0]
for i, peak in enumerate(peaks):
mask = cv2.inRange(h, peak, peak)
blob = cv2.bitwise_and(image, image, mask=mask)
_, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for j, contour in enumerate(contours):
bbox = cv2.boundingRect(contour)
contour_mask = np.zeros_like(mask)
cv2.drawContours(contour_mask, contours, j, 255, -1)
region = blob.copy()[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]]
region_mask = contour_mask[bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]]
region_masked = cv2.bitwise_and(region, region, mask=region_mask)
result = cv2.bitwise_and(blob, blob, mask=contour_mask)
top_left, bottom_right = (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3])
cv2.rectangle(result, top_left, bottom_right, (255, 255, 255), 2)
cv2.imshow('image',result)
cv2.waitKey(0)
cv2.destroyAllWindows()