如何使用Python图像处理功能检测和识别图像中的复杂形状?

问题描述

我是StackOverflow的新手。 我试图按照钻石的名称和形状来检测形状。various shapes of diamond。为了进行形状检测,我使用了https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/中给出的程序 这是代码:

import cv2
import imutils
class ShapeDetector:
    def __init__(self):
        pass
    def detect(self,c):
        # initialize the shape name and approximate the contour
        shape = "unidentified"
        peri = cv2.arcLength(c,True)
        approx = cv2.approxPolyDP(c,0.04 * peri,True)

        # if the shape is a triangle,it will have 3 vertices
        if len(approx) == 3:
            shape = "triangle"
            # if the shape has 4 vertices,it is either a square or
            # a rectangle
        elif len(approx) == 4:
            # compute the bounding box of the contour and use the
            # bounding box to compute the aspect ratio
            (x,y,w,h) = cv2.boundingRect(approx)
            ar = w / float(h)
            # a square will have an aspect ratio that is approximately
            # equal to one,otherwise,the shape is a rectangle
            shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"
        # if the shape is a pentagon,it will have 5 vertices
        elif len(approx) == 5:
            shape = "pentagon"
        # otherwise,we assume the shape is a circle
        else:
            shape = "circle"
        # return the name of the shape
        return shape
# -----------------
image = cv2.imread(shape_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,20,255,cv2.THRESH_BINARY)[1]

# find contours in the thresholded image and initialize the
# shape detector
cnts = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
sd = ShapeDetector()

# loop over the contours
for c in cnts:
    # compute the center of the contour,then detect the name of the
    # shape using only the contour
    M = cv2.moments(c)
    cX = int((M["m10"] / M["m00"]) * ratio)
    cY = int((M["m01"] / M["m00"]) * ratio)
    shape = sd.detect(c)
    # multiply the contour (x,y)-coordinates by the resize ratio,# then draw the contours and the name of the shape on the image
    c = c.astype("float")
    c *= ratio
    c = c.astype("int")
    cv2.drawContours(image,[c],-1,(0,0),2)
    cv2.putText(image,shape,(cX,cY),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255),2)
print("The Shape of Object is: ",shape)
# show the output image
cv2.imshow("Image",image)
cv2.waitKey(0)
cv2.destroyAllWindows()

但是,我无法为此取得完美的结果。有没有办法找出图像中给出的形状。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)