Python开发系统
以下是一个基于Python和OpenCV的简单图像检测系统开发示例,包含目标检测、颜色检测和边缘检测功能:
一、环境搭建
1. 安装依赖
pip install opencv-python numpy matplotlib
2. 准备测试图片
下载示例图片或使用本地图片(如 test.jpg )。
二、基础功能实现
1. 目标检测(使用预训练模型)
import cv2
import numpy as np
def object_detection(image_path):
# 加载COCO类别名称
with open('coco.names', 'r') as f:
classes = f.read().strip().split('\n')
# 加载YOLOv3模型配置和权重
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
layer_names = net.getLayerNames()
output_layers = [layer_names[i-1] for i in net.getUnconnectedOutLayers()]
# 读取图像并预处理
img = cv2.imread(image_path)
height, width, channels = img.shape
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
# 前向传播
net.setInput(blob)
outs = net.forward(output_layers)
# 解析检测结果
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5: # 置信度阈值
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w/2)
y = int(center_y - h/2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 非极大值抑制去重
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 在图像上绘制检测框
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
confidence = confidences[i]
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(img, f"{label} {confidence:.2f}", (x, y+30), font, 2, (0, 255, 0), 2)
return img
2. 颜色检测(以红色为例)
def color_detection(image_path, color='red'):
img = cv2.imread(image_path)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 红色的HSV范围(分两个区间处理)
if color == 'red':
lower_red1 = np.array([0, 120, 70])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([170, 120, 70])
upper_red2 = np.array([180, 255, 255])
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
mask = mask1 + mask2
else:
# 其他颜色可自定义HSV范围(如绿色:lower=[35, 43, 46], upper=[77, 255, 255])
mask = np.zeros_like(hsv[:, :, 0])
# 轮廓检测
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 100: # 过滤小面积
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
return img
3. 边缘检测(Canny算法)
def edge_detection(image_path):
img = cv2.imread(image_path, 0) # 转为灰度图
edges = cv2.Canny(img, 100, 200) # 调整阈值控制边缘灵敏度
return edges
三、系统主界面
import matplotlib.pyplot as plt
def main():
image_path = 'test.jpg' # 替换为你的图片路径
while True:
print("\n==== OpenCV图像检测系统 ====")
print("1. 目标检测(YOLOv3)")
print("2. 颜色检测(红色)")
print("3. 边缘检测(Canny)")
print("4. 退出系统")
choice = input("请选择功能:")
if choice == '1':
result = object_detection(image_path)
elif choice == '2':
result = color_detection(image_path)
elif choice == '3':
result = edge_detection(image_path)
elif choice == '4':
print("系统退出!")
break
else:
print("无效选择!")
continue
# 显示结果
plt.figure(figsize=(10, 6))
if choice == '3':
plt.imshow(result, cmap='gray')
else:
plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.title(f"检测结果 - 功能{choice}")
plt.show()
if __name__ == "__main__":
main()
四、运行说明
1. 下载模型文件
- 从YOLO官网下载 yolov3.cfg 和 yolov3.weights
- 下载COCO类别名称文件,保存为 coco.names
2. 运行代码
python image_detection_system.py
3. 功能扩展方向
- 更换模型(如YOLOv5、SSD)
- 支持视频流检测( cv2.VideoCapture() )
- 添加自定义颜色检测功能
- 集成图像预处理(降噪、缩放)
注意事项
- 目标检测模型较大,首次运行可能需要下载时间
- 颜色检测需根据实际场景调整HSV阈值
- 边缘检测阈值可通过滑动条动态调整(需添加GUI界面)
需要进一步优化某个功能或添加特定检测需求(如人脸检测、二维码识别),可以随时告诉我!