opencv viz
时间: 2025-04-19 10:30:32 浏览: 21
### OpenCV 可视化模块特性与使用
#### 图像显示基础
OpenCV 提供了 `cv2.imshow()` 函数用于展示图像窗口。此函数接受两个参数:一个是窗口名称字符串;另一个是要显示的图像矩阵[^1]。
```python
import cv2
image = cv2.imread('example.jpg')
cv2.imshow('Image Window', image)
cv2.waitKey(0) # Wait indefinitely until a key is pressed
cv2.destroyAllWindows()
```
#### 绘制几何形状和文本
除了简单的图像显示之外,还可以利用绘图函数来增强视觉效果。这些函数允许绘制线条、矩形、圆圈以及添加文字说明:
- **画线**: 使用`cv2.line()`
- **画矩形框**: 使用`cv2.rectangle()`
- **画圆形标记**: 使用`cv2.circle()`
- **写入文本标签**: 使用`cv2.putText()`
```python
# Drawing shapes on images
start_point = (50, 50)
end_point = (200, 200)
color = (255, 0, 0) # Blue color in BGR format
thickness = 2 # Line thickness of 2 px
cv2.line(image, start_point, end_point, color, thickness)
top_left_corner = (100, 100)
bottom_right_corner = (300, 300)
rectangle_color = (0, 255, 0) # Green color in BGR format
cv2.rectangle(image, top_left_corner, bottom_right_corner, rectangle_color, thickness)
center_coordinates = (400, 400)
radius = 30
circle_color = (0, 0, 255) # Red color in BGR format
cv2.circle(image, center_coordinates, radius, circle_color, thickness)
font = cv2.FONT_HERSHEY_SIMPLEX
text_position = (50, 50)
font_scale = 1
text_color = (255, 255, 255) # White text color
line_type = 2 # Line type can be one of the following: LINE_4, LINE_8 or LINE_AA.
cv2.putText(image,'Text Here!', text_position , font,
font_scale,text_color,line_type)
```
#### 创建自定义图形界面
对于更复杂的交互需求,可以考虑集成其他GUI库如Tkinter 或 PyQt 来构建完整的应用程序环境。然而,在某些情况下仅通过OpenCV本身也可以实现基本的鼠标事件处理机制,从而支持用户点击操作并响应特定行为。
```python
def draw_circle(event,x,y,flags,param):
global drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.circle(img,(x,y),5,(255,255,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
cv2.circle(img,(x,y),5,(255,255,255),-1)
drawing = False
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('Drawing Board')
cv2.setMouseCallback('Drawing Board',draw_circle)
while(True):
cv2.imshow('Drawing Board', img)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break
cv2.destroyAllWindows()
```
阅读全文
相关推荐

















