gharabat
gharabat

Reputation: 177

How can I draw a rectangle around a colored object in open cv python?

How can I draw a rectangle on the white object (in mask window), that appears in the original cam (in frame window) see image

my code:

    import cv2
    import numpy as np
    cap = cv2.VideoCapture(0)

    while(1):
        # Take each frame
        _, frame = cap.read()
        # Convert BGR to HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # define range of red color in HSV
        lower_blue = np.array([0,89,190])
        upper_blue = np.array([180,255,255])
        # Threshold the HSV image to get only red colors
        mask = cv2.inRange(hsv, lower_blue, upper_blue)
        # Bitwise-AND mask and original image
        res = cv2.bitwise_and(frame,frame, mask= mask)
        cv2.imshow('frame',frame)
        cv2.imshow('mask',mask)
        cv2.imshow('res',res)
        k = cv2.waitKey(5) & 0xFF
        if k == 27:
            break
    cv2.destroyAllWindows()

Sorry for my bad English, I'm doing my best to improve it.

Upvotes: 0

Views: 5474

Answers (2)

MK 62665
MK 62665

Reputation: 123

Like Tiphel said, you can use cv2.findContours and cv2.drawContours. Alternatively, after getting the contours, you can draw a box using cv2.boundingRect() function too. This returns 4 arguments, say, x,y, w and h. x,y represent a point and w, h represent the width of height of the rectangle respectively. You can then use cv2.rectangle to draw the rectangle. You can fit other shapes too similarly, like ellipses, circles, etc.

i, contours, heirarchy = cv2.findContours(a_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cont_sorted = sorted(cnts2, key=cv2.contourArea, reverse=True)[:5]

x,y,w,h = cv2.boundingRect(cont_sorted[0])

cv2.rectangle(a,(x,y),(x+w,y+h),(0,0,255),5)

Here, a_thresh is the binary image after thresholding input image. In the cv2.rectange() function, the first argument corresponds to the image on which you want to draw, fourth argument specifies the color and fifth specifies the thickness of line used to draw the rectangle.

Also, I use 'sorted' to get the top 5 contours in terms of their size and ideally my object of interest would be the one with the largest area.

You can find documentation for these online. I suggest you go through the documentation for all functions used above to use it appropriately for your application!

Upvotes: 2

Tiphel
Tiphel

Reputation: 323

Use cv2.findContours to find the object on your masked image then cv2.drawContours to display it.

Doc here

Upvotes: 0

Related Questions