

本人初学者一名,上图是我提取出来的轮廓,图像去噪效果不是很好,还是有很多,效果太差,分别使用了sobel,canny锐化边缘,用了高斯模糊除了,效果还是没有明显改善,向各位请教一下有什么好的方法能够吧图像中的六边形高质量的完全提取出来吗


安装imutils
pip install imutils
代码
ShapeDetector.Py
import cv2
class ShapeDetector:
def __init__(self):
pass
def detect(self, c):
shape = ""
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
if len(approx) == 6:
shape ="六边形"
return shape
detect_shapes.py
from pyimagesearch.shapedetector import ShapeDetector
import argparse
import imutils
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="输入图像的路径")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
resized = imutils.resize(image, width=300)
ratio = image.shape[0] / float(resized.shape[0])
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
sd = ShapeDetector()
for c in cnts:
M = cv2.moments(c)
cX = int((M["m10"] / M["m00"]) * ratio)
cY = int((M["m01"] / M["m00"]) * ratio)
shape = sd.detect(c)
c = c.astype("float")
c *= ratio
c = c.astype("int")
cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (255, 255, 255), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
python detect_shapes.py --image 你的图形文件.png