如何解决cv2.findContours() 和 cv2.drawContours() 不显示预期结果
我试图找出下图中每个形状的轮廓:1
我尝试了以下代码:
!pip install opencv-python
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from google.colab import drive
from google.colab.patches import cv2_imshow
drive.mount('/content/drive')
path='/content/drive/My Drive/NewApproach.png'
img= cv.imread(path,cv.IMREAD_UNCHANGED)
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
blur=cv.GaussianBlur(gray,(13,13),0)
blur8 = blur.astype(np.uint8)
canny=cv.Canny(blur8,110,120,3)
dilated=cv.dilate(canny,(-1,-1),iterations=2)
(cnt,heirarchy)=cv.findContours(dilated.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)
rgb=cv.cvtColor(img,cv.COLOR_BGR2RGB)
cv.drawContours(rgb,cnt,-1,(0,255,0),2)
def find_contour_areas(cnt):
areas=[]
for contour in cnt:
cont_area=cv.contourArea(contour)
areas.append(cont_area)
return areas
sorted_contours_by_area=sorted(cnt,key=cv.contourArea,reverse=True)
for sc in sorted_contours_by_area:
duplicate_img=cv.imread(path,cv.IMREAD_UNCHANGED)
#duplicate_img_color = cv.cvtColor(duplicate_img,cv.COLOR_GRAY2BGR)
#cv.drawContours(duplicate_img_color,[sc],3)
cv.drawContours(duplicate_img,3)
cv.waitKey(0)
cv2_imshow(duplicate_img)
cv.waitKey(0)
但结果是采用下图所示的形状:2 与人们第一眼看到的形状不完全相同。
有人可以帮我解决这个问题吗?提前致谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。