Skip to content
Advertisement

How to find contours in a region of interest in image using opencv and Python?

while(True):

    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    a, b = 0, 0

    height, width, layers = frame.shape
    start_height = height - height
    left_x = width - 500

    #right_area = frame[y:y+height, x:x+300]
    #left_area = frame[y:y+height,]

    black_min = np.array([0, 0, 0], np.uint8)
    black_max = np.array([179, 255, 70], np.uint8)

    red_min = np.array([0, 70, 50], np.uint8)
    red_max = np.array([20, 255, 255], np.uint8)

    red1 = np.array([170, 70, 50], np.uint8)
    red2 = np.array([180, 255, 255], np.uint8)

    red_mask = cv2.inRange(hsv, red1, red2)
    red_mask2 = cv2.inRange(hsv, red_min, red_max)
    kernel = np.ones((7, 7), "uint8")

    red_mask = cv2.dilate(red_mask, kernel)
    res_red = cv2.bitwise_and(frame, frame, mask=red_mask)
    red_mask2 = cv2.dilate(red_mask2, kernel)
    res_red2 = cv2.bitwise_and(frame, frame, mask=red_mask2)

    area1 = frame[a:a + height, b:b + 300]
    area2 = frame[a:a + height, left_x:left_x + 500]

    cnts, _ = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


    for pic, c in enumerate(cnts):

        area = cv2.contourArea(c)
        if (700 > area > 350):
            x,y,w,h = cv2.boundingRect(c)
            cv2.rectangle(frame, (x, y),(x + w, y + h),(0, 0, 255), 2)
            cv2.putText(frame, "Red detected", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255))


    cv2.imshow("Video from camera", frame)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

I belive that for C++ the solution looks like this:

findContours(Mask(cv::Rect(x,y,width,height)), contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0,0) );

How can I change this line to get the results I want?

this is the area I’m interested in frame[a:a + height, b:left_x + 300] Thanks in advance!

Advertisement

Answer

your code looks strange to me, here a snippet with a line

QString line="144,81:626,232";
QStringList points = line.split(":");
qDebug()<< points[0];
qDebug()<< points[1];
QRectF rectangle;
QStringList xy1 = points[0].split(",");
qDebug()<< xy1[0];
qDebug()<< xy1[1];
auto x1=QString(xy1[0]).toFloat();
auto y1=QString(xy1[1]).toFloat();

rectangle.setTopLeft(QPointF(x1,y1));

xy1 = points[1].split(",");
qDebug()<< xy1[0];
qDebug()<< xy1[1];
x1=QString(xy1[0]).toFloat();
y1=QString(xy1[1]).toFloat();

rectangle.setBottomRight(QPointF(x1,y1));

qDebug() << "Rec: " << rectangle;
return 0;

so for the input "144,81:626,232"; you get the output:

Rec:  QRectF(144,81 482x151)

because that is the way qt print rectangle objects-> topLeftPoint wxh

Advertisement