OpenCV: draw a rectangle around a region
Asked Answered
W

4

120

How can I use OpenCV in Python to draw rectangles around some regions within an image for object detection purposes?

Woden answered 18/5, 2014 at 10:20 Comment(0)
W
280

Use cv2:

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), color=(255,0,0), thickness=2)


x1,y1 ------
|          |
|          |
|          |
--------x2,y2

[edit] to append the follow-up questions below:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever
Whitehurst answered 18/5, 2014 at 10:32 Comment(11)
I just tried importing cv2. I get: DLL load failed: %1 is not a valid Win32 application. I'm running win7 64-bit. And spyder and scikit libraries and everything's running 64-bit.Woden
@Woden download 64 bit install binaries from here lfd.uci.edu/~gohlke/pythonlibs/#opencvRutherfurd
Thanks! I've downloaded it... any idea how to make it work with Anaconda's Spyder?Woden
Okay I've got it working on Spyder. @berak, how can I display or save the image? Should I assign it to a numpy array? I tried ig = ImageViewer( cv2.rectangle(image1, (10, 10), (100, 100), (255,0,0), 2)) ig.show() but got this error: TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)Woden
how to find these co-ordinates x1,y1 and x2,y2 ?Tarragona
@Manoranjan you'll have to either experiment by starting the rectangle somewhere random on the image and adjusting the coordinates from there, or use another graphics application that you draw the box where you'd like it and pull the coordinates from that.Plumbism
@berak, I have coordinates in a list called bbox[0 to bbox[3]. When I do cv2.rectangle() it works and I know bottom left is (bbox[0], bbox[3]` and top right is bbox[2], bbox[1]. But when I go to crop, my y's are reversed so I end up with a crop of shape (0, width, channels).Messinger
Hi, how do you draw a dotted line instead of a normal line? I tried referring to the documentation adding the parameter of lineType= but it don't seems to work.Fosque
Does the coordinates system of CV start from (0, 0) (Being top left or (1, 1)?Carolanncarole
worth mentioning if this is inplace or notSword
@Carolanncarole 0, 0, as python is 0-based.Sword
H
17

As the other answers said, the function you need is cv2.rectangle(), but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top) and (right, bottom). Or, equivalently, (xmin, ymin) and (xmax, ymax).

Holstein answered 3/7, 2019 at 17:5 Comment(0)
R
15

You can use cv2.rectangle():

cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)

Draws a simple, thick, or filled up-right rectangle.

The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.

Parameters
    img   Image.
    pt1   Vertex of the rectangle.
    pt2    Vertex of the rectangle opposite to pt1 .
    color Rectangle color or brightness (grayscale image).
    thickness  Thickness of lines that make up the rectangle. Negative values,
    like CV_FILLED , mean that the function has to draw a filled rectangle.
    lineType  Type of the line. See the line description.
    shift   Number of fractional bits in the point coordinates.

I have a PIL Image object and I want to draw rectangle on this image. I want to use opencv2 and draw rectangle, and then convert back to PIL Image object. Here is how I do it:

# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)
Roughish answered 13/12, 2018 at 14:44 Comment(0)
G
1

The code for drawing a rectangle on an image is:

cv2.rectangle(image, pt1, pt2, color, thickness)

where pt1 is starting point-->(x,y) and pt2 is end point-->(x+w,y+h).

Gongorism answered 1/11, 2021 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.