OpenCV:在区域周围绘制矩形

120 投票
4 回答
294751 浏览
提问于 2025-04-18 06:54

我想知道怎么在Python中使用OpenCV这个工具,在图片上画出矩形框,以便进行物体检测。

4 个回答

1

在图片上画一个矩形的代码是:

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

这里的 pt1 是矩形的起始点,也就是左上角的坐标 (x,y),而 pt2 是矩形的结束点,也就是右下角的坐标 (x+w,y+h)。

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

正如其他回答所说,你需要用到的函数是 cv2.rectangle()。不过要记住,边框框的顶点坐标如果是用元组表示的话,必须是整数。而且这些坐标的顺序要是 (左边, 上边)(右边, 下边)。或者说,也可以用 (最小x, 最小y)(最大x, 最大y) 来表示。

280

使用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

撰写回答