以下是一些常见的视觉检测任务的Python代码示例:\n\n1. 人脸检测:\n\npython\nimport cv2\n\n# 加载人脸检测器\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n# 读取图像\nimage = cv2.imread('image.jpg')\n\n# 将图像转换为灰度图\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# 检测人脸\nfaces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))\n\n# 在图像上绘制矩形框标记人脸位置\nfor (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n# 显示结果图像\ncv2.imshow('Face Detection', image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n2. 目标检测(使用YOLOv3模型):\n\npython\nimport cv2\nimport numpy as np\n\n# 加载YOLOv3配置和权重文件\nnet = cv2.dnn.readNet('yolov3.cfg', 'yolov3.weights')\n\n# 获取所有输出层的名称\nlayer_names = net.getLayerNames()\noutput_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\n# 读取图像\nimage = cv2.imread('image.jpg')\n\n# 获取图像尺寸\nheight, width, channels = image.shape\n\n# 将图像转换为输入网络的blob\nblob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)\n\n# 设置blob为网络的输入\nnet.setInput(blob)\n\n# 前向传播\nouts = net.forward(output_layers)\n\n# 解析输出结果\nclass_ids = []\nconfidences = []\nboxes = []\nfor out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5:\n # 目标框的中心坐标和宽高\n center_x = int(detection[0] * width)\n center_y = int(detection[1] * height)\n w = int(detection[2] * width)\n h = int(detection[3] * height)\n\n # 计算目标框的左上角坐标\n x = int(center_x - w / 2)\n y = int(center_y - h / 2)\n\n # 存储目标框相关信息\n class_ids.append(class_id)\n confidences.append(float(confidence))\n boxes.append([x, y, w, h])\n\n# 非最大抑制,剔除重叠的目标框\nindexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n\n# 在图像上绘制目标框和类别标签\nfont = cv2.FONT_HERSHEY_SIMPLEX\nfor i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(class_ids[i])\n confidence = confidences[i]\n color = (0, 255, 0)\n cv2.rectangle(image, (x, y), (x+w, y+h), color, 2)\n cv2.putText(image, label, (x, y-10), font, 0.5, color, 2)\n\n# 显示结果图像\ncv2.imshow('Object Detection', image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n以上代码示例仅供参考,实际使用时需要根据具体的任务和模型进行适当的修改和调整。

Python视觉检测代码示例 - 人脸检测、目标检测(YOLOv3)

原文地址: https://www.cveoy.top/t/topic/mAAW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录