[英]How to draw contours using opencv in Python?
我已經對以下圖像進行了預處理:
現在,我想使用findContours
方法從圖像中查找單元格,然后使用drawContours
為圖像中的每個單元格繪制輪廓。 我這樣做,但是什么也沒顯示。
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
我收到以下錯誤。
輪廓不是numpy數組,也不是標量
另一個答案對我沒有幫助。
我也使用以下解決方案。
contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
ctr = numpy.array(contours).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(img, ctr, -1, (0, 255, 0), 3)
但是此解決方案並未在給定圖像上繪制任何內容。
更新 ,OpenCV 4.0更改cv2.findContours
。 因此,我修改了代碼示例。 還有更一般的方法:
cnts, hiers = cv2.findContours(...)[:-2]
cv2.findContours
返回一個元組,而不僅僅是輪廓。 您可以這樣:
## Find contours
if cv2.__version__.startswith("3."):
_, contours, _ = cv2.findContours(bimg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
contours, _ = cv2.findContours(bimg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
## Draw contours
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
相關類似問題:
cv2.findContours
返回的元組具有以下形式(im, contours, hierarchy)
,其中im
是具有可視化contours
的圖像, contours
是具有兩個numpy數組的元組,形式為(x_values, y_values)
並且heirarchy
取決於檢索模式。 由於您使用的是CV_RETR_EXTERNAL,所以heirarchy
沒有太大的意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.