Find Rotated Rectangle in OpenCV Python

孤人 提交于 2021-01-29 20:22:09

问题


i have python function like below

def getContours(img, imgContour):
    contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 1000:
            cv2.drawContours(imgContour, contours, -1, (255, 0, 255), 7)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            # print(len(approx))
            x, y, w, h = cv2.boundingRect(approx)
            #cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 5)

            if len(approx) == 3:
                cv2.putText(imgContour, "Segitiga", (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, 0, 2)
            elif len(approx) == 4:
                (x, y, w, h) = cv2.boundingRect(approx)
                ar = w / float(h)
                print(ar)
                if ar >= 0.95 and ar <= 1.05:
                    cv2.putText(imgContour, "Persegi", (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, 0, 2)
                else:
                    cv2.putText(imgContour, "Segi Panjang", (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, 0, 2)
            else:
                cv2.putText(imgContour, "Lingkaran/Octagon", (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, 0, 2)

how do I know that the rectangle detected in the image has a rotation of 45 (rhombus)? I haven't found a function in opencv related to rotation detection


回答1:


From what i think, you are asking for how to get a rotated rect to capture some 45degree placed item.

Take a look here use cv::minAreaRect function

rect = cv.minAreaRect(cnt)
box = cv.boxPoints(rect)
box = np.int0(box)
cv.drawContours(img,[box],0,(0,0,255),2)

https://docs.opencv.org/3.4/dd/d49/tutorial_py_contour_features.html



来源:https://stackoverflow.com/questions/62596734/find-rotated-rectangle-in-opencv-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!