我import cv
在python代码中遇到了麻烦。
我的问题是我需要在图像的感兴趣区域周围绘制一个矩形。如何在python中完成?我正在执行对象检测,并想在我相信在图像中找到的对象周围绘制一个矩形。
Answers:
请不要尝试使用旧的cv模块,请使用cv2:
import cv2
cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)
x1,y1 ------
| |
| |
| |
--------x2,y2
[编辑]追加以下后续问题:
cv2.imwrite("my.png",img)
cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever
您可以使用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 Image对象,我想在该图像上绘制矩形,但是PIL的ImageDraw.rectangle()方法无法指定线宽。 我需要将Image对象转换为opencv2的图像格式,并绘制矩形并转换回Image对象。这是我的方法:
# 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)
DLL load failed: %1 is not a valid Win32 application
。我正在运行Win7 64位。spyder和scikit库以及所有运行的都是64位。