问题描述
我尝试使用 cv2.findContours
在我的图像中找到轮廓。因此,当它使用 CV_8UC1 图像时,我尝试在它是 32 位之前用 dtype=np.uint8
转换我的数组。但是我正在丢失信息。还有其他办法吗?
第二个问题是边界框。信息保存在rect
中,但没有绘制在图片中。有谁知道为什么?
这是我的 32 位图片/数组:
这是我添加 dtype=np.uint8
时的照片:
img_hr = np.array(b[1],dtype=np.uint8)
img_hr=img_hr*255
plt.imshow(img_hr)
hierachy,img_threshold = cv2.threshold(img_hr,100,255,cv2.THRESH_BINARY)
contours,_ = cv2.findContours(img_threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img_threshold,contours,-1,(0,0),2,cv2.LINE_AA)
for cnt in contours:
rect = cv2.minAreaRect(cnt)
Box = cv2.BoxPoints(rect)
Box = np.int0(Box)
cv2.drawContours(img_threshold,[Box],255),2)
cv2.circle(img_threshold,(int(rect[0][0]),int(rect[0][1])),5,(255,-1)
plt.imshow(img_threshold)
我希望你能理解我的问题。如果没有请询问。我感谢您的帮助。谢谢
解决方法
我自己找到了解决方案:
首先我使用 32 位图像在 32 位图像中找到带有 cv2.threshold
的轮廓。在此之后,我将 32 位数组转换为 8 位 np.array(img_threshold_32bit,dtype=np.uint8)
而不会丢失任何轮廓。
所以现在 cv2.drawContours
的输入是一个 8 位数组。
但我仍然有一个问题,即未在图中绘制边界框。有什么想法吗?
代码如下:
img_hr = np.array(b[1])
hierachy,img_threshold_32bit = cv2.threshold(img_hr,100,255,cv2.THRESH_BINARY)
img_8bit = np.array(img_threshold_32bit,dtype=np.uint8)
contours,_ = cv2.findContours(img_8bit,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img_8bit,contours,-1,(0,0),2,cv2.LINE_AA)
for cnt in contours:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img_8bit,[box],255),2)
cv2.circle(img_8bit,(int(rect[0][0]),int(rect[0][1])),5,(255,-1)
plt.imshow(img_8bit)
,
因为你自己画 drawContours 只绘制轮廓轮廓或填充轮廓。 您必须使用 boundingRec 或 minAreaRect 为每个轮廓找到一个矩形坐标,然后使用 opencv 的绘图函数绘制它
检查此示例代码 https://github.com/birolkuyumcu/opencvbook_python/blob/master/Ders6/Ders6.py#L114