简体   繁体   中英

Find Rotated Rectangle in OpenCV Python

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

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM