OpenCV:在一个区域周围画一个矩形

118
如何在Python中使用OpenCV来绘制矩形框,以便在图像中标记出一些区域,用于目标检测的目的?
4个回答

277
请不要使用旧的cv模块,改用cv2。
import cv2

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


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

追加以下后续问题:
cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

@user961627 从这里下载64位安装二进制文件 http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv - M4rtini
1
谢谢!我已经下载了它... 有什么办法可以让它在Anaconda的Spyder中工作吗? - user961627
1
CV的坐标系是从(0, 0)(左上角)开始还是从(1, 1)开始? - Royi
值得一提的是,这是否已经就位。 - undefined
@Royi 0, 0,因为Python是从0开始计数的。 - undefined
显示剩余7条评论

16

正如其他答案所说,你需要使用的函数是cv2.rectangle(),但请记住,如果将边界框定点放在元组中,则它们的坐标需要为整数,并且它们必须按照(left, top)(right, bottom)或等价的(xmin, ymin)(xmax, ymax)的顺序。


15

您可以使用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.

我有一个PIL图像对象,想在这个图像上绘制矩形。我想使用opencv2来绘制矩形,然后将其转换回PIL图像对象。这是我的做法:

# 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)

1
在图像上绘制矩形的代码如下:
cv2.rectangle(image, pt1, pt2, color, thickness)

这里的pt1是起点 --> (x,y),而pt2是终点 --> (x+w,y+h)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接