常见视觉检测python代码
以下是一些常见的视觉检测任务的Python代码示例:
- 人脸检测:
import cv2
# 加载人脸检测器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 读取图像
image = cv2.imread('image.jpg')
# 将图像转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# 在图像上绘制矩形框标记人脸位置
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Face Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 目标检测(使用YOLOv3模型):
import cv2
import numpy as np
# 加载YOLOv3配置和权重文件
net = cv2.dnn.readNet('yolov3.cfg', 'yolov3.weights')
# 获取所有输出层的名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 读取图像
image = cv2.imread('image.jpg')
# 获取图像尺寸
height, width, channels = image.shape
# 将图像转换为输入网络的blob
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
# 设置blob为网络的输入
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)
# 存储目标框相关信息
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 非最大抑制,剔除重叠的目标框
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 在图像上绘制目标框和类别标签
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(class_ids[i])
confidence = confidences[i]
color = (0, 255, 0)
cv2.rectangle(image, (x, y), (x+w, y+h), color, 2)
cv2.putText(image, label, (x, y-10), font, 0.5, color, 2)
# 显示结果图像
cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
以上代码示例仅供参考,实际使用时需要根据具体的任务和模型进行适当的修改和调整。
原文地址: https://www.cveoy.top/t/topic/i5Z0 著作权归作者所有。请勿转载和采集!