import os
import cv2
import numpy as np
示例变量(需要根据实际情况定义)
image_folder = ‘C:/Users/vzhiwei/Desktop/yolov3/image/’ # 确保这个路径是正确的
original_images = [‘image1.jpg’, ‘image2.jpg’, ‘image3.jpg’] # 确保这些文件名是正确的
def pre_process(image, target_size):
# 示例预处理函数
resized = cv2.resize(image, target_size)
return resized / 255.0 # 假设归一化
需要根据实际情况定义
shapeIn = (1, 640, 640, 3)
shapeOut0 = (1, 85, 20, 20)
shapeOut1 = (1, 85, 40, 40)
shapeOut2 = (1, 85, 80, 80)
class DummyDPU:
def execute_async(self, input_data, output_data):
# 模拟DPU执行
return 1
def wait(self, job_id):
# 模拟等待DPU完成
pass
dpu = DummyDPU()
input_data = np.zeros(shapeIn, dtype=np.float32)
output_data = [np.zeros(shapeOut0), np.zeros(shapeOut1), np.zeros(shapeOut2)]
def evaluate(yolo_outputs, image_size, class_names, anchors):
# 示例评估函数
boxes = [(10, 10, 100, 100)]
scores = [0.9]
classes = [0]
return boxes, scores, classes
def draw_boxes(image, boxes, scores, classes):
# 示例绘制函数
for box in boxes:
cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
cv2.imshow(‘Image’, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def run(image_index, display=False):
try:
# 确保 image_index 在 original_images 列表的范围内
if image_index < 0 or image_index >= len(original_images):
print(“Error: image_index out of range”)
return
image_path = os.path.join(image_folder, original_images[image_index])
print(f"Reading image from: {image_path}")
# 读取输入图像
input_image = cv2.imread(image_path)
# 检查图像是否成功读取
if input_image is None:
print(f"Error: Failed to read image {original_images[image_index]} from path {image_path}")
return
# 预处理
image_size = input_image.shape[:2]
# 将预处理大小改为(640, 640)以匹配DPU输入
image_data = np.array(pre_process(input_image, (640, 640)), dtype=np.float32)
# 将数据传送到DPU并触发执行
input_data[0, ...] = image_data.reshape(shapeIn[1:])
job_id = dpu.execute_async(input_data, output_data)
dpu.wait(job_id)
# 获取输出数据
conv_out0 = np.reshape(output_data[0], shapeOut0)
conv_out1 = np.reshape(output_data[1], shapeOut1)
conv_out2 = np.reshape(output_data[2], shapeOut2)
yolo_outputs = [conv_out0, conv_out1, conv_out2]
# 从YOLOv3解码输出
boxes, scores, classes = evaluate(yolo_outputs, image_size, class_names, anchors)
if display:
_ = draw_boxes(input_image, boxes, scores, classes)
print("检测到的对象数量: {}".format(len(boxes)))
except Exception as e:
print(f"Error occurred: {e}")
打印 original_images 的长度以调试
print(“Number of images:”, len(original_images))
示例调用
run(2, display=True)
运行上述代码之后 会提示内核终端