点击查看代码
import time
import cv2
import numpy as np
from datetime import datetime
cfg_path= r'./sit-page/yolov7-tiny.cfg'
weights_path= r'./sit-page/yolov7-tiny_10000.weights'
data_path= r'./sit-page/classes.names'
image_path= r'./ng/TRIODE_4_19_20240718165226_OK_.png'
with open(data_path, 'r') as f:
class_names = f.read().strip().split('\n')
net = cv2.dnn.readNetFromDarknet(cfg_path, weights_path)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
image = cv2.imread(image_path)
height, width = image.shape[:2]
start = time.time()
blob = cv2.dnn.blobFromImage(image, scalefactor=1/255.0, size=(256, 256), swapRB=True, crop=False)
net.setInput(blob)
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
layer_outputs = net.forward(output_layers)
conf_threshold = 0.5
nms_threshold = 0.4
boxes, confidences, class_ids = [], [], []
for output in layer_outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > conf_threshold:
box = detection[:4] * np.array([width, height, width, height])
center_x, center_y, w, h = box.astype('int')
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, int(w), int(h)])
confidences.append(float(confidence))
class_ids.append(class_id)
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
print("indices:",indices)
for i in indices.flatten():
x, y, w, h = boxes[i]
print("x:", x)
print("y:", y)
print("w:", w)
print("h:", h)
color = (0, 255, 0)
label = f'{class_names[class_ids[i]]}: {confidences[i]:.2f}'
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
output_filename = f"./test_rec/rgb_image_{timestamp}.png"
end = time.time()
print(f"cost time :{end - start}")
cv2.imwrite(output_filename, image)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)