分类检测
import cv2
import numpy as np
import tensorflow as tf
import os
# 使用轻量级模型替代VGG16
def load_lightweight_model():
try:
# 尝试使用MobileNetV2或EfficientNet
model = tf.keras.applications.MobileNetV2(
weights='imagenet',
include_top=True,
input_shape=(224, 224, 3)
)
return model
except:
# 如果还不行,使用更小的模型
model = tf.keras.applications.MobileNet(
weights='imagenet',
include_top=True,
input_shape=(224, 224, 3)
)
return model
# 加载模型
model = load_lightweight_model()
print("模型加载成功")
# 简化版的selective_search函数
def selective_search(image):
# 使用OpenCV的简单区域提议方法
ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
ss.setBaseImage(image)
ss.switchToSelectiveSearchFast()
rects = ss.process()
return rects[:100] # 只取前100个区域
# 调整图像大小函数
def resize(region, size):
return cv2.resize(region, size)
# 简化的分类和回归函数
def classify_and_regress(features):
# 这里简化处理,实际需要根据模型输出处理
predictions = tf.keras.applications.imagenet_utils.decode_predictions(features)
class_label = predictions[0][0][1] # 取最可能的类别
bbox = [0, 0, 224, 224] # 简化边界框
return class_label, bbox
def show_result(proposal, class_label, bbox,idx):
print(f"类别: {class_label}, 边界框: {bbox}")
x1,y1,x2,y2 = bbox
cv2.rectangle(proposal,(x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(proposal, class_label, (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
out_file = f"result_{idx}.jpg"
cv2.imwrite(out_file, proposal)
print(f"resulut is saved as {out_file}")
# 在实际应用中这里会显示图像
# 主程序
try:
# 加载图像
image = cv2.imread('image.jpg')
if image is None:
print("无法加载图像,请检查文件路径")
# 创建测试图像
image = np.random.randint(0, 255, (300, 300, 3), dtype=np.uint8)
print("开始提取候选区域...")
# 提取候选区域
region_proposals = selective_search(image)
print(f"找到 {len(region_proposals)} 个候选区域")
# 限制处理数量以避免内存不足
max_proposals = min(10, len(region_proposals))
# 遍历候选区域
for i, proposal_rect in enumerate(region_proposals[:max_proposals]):
x, y, w, h = proposal_rect
proposal_region = image[y:y+h, x:x+w]
if proposal_region.size == 0:
continue
print(f"处理区域 {i+1}/{max_proposals}")
# 调整候选区域大小
resized_proposal = resize(proposal_region, (224, 224))
# 预处理图像
processed_img = tf.keras.applications.mobilenet.preprocess_input(
np.expand_dims(resized_proposal, axis=0)
)
# 特征提取
features = model.predict(processed_img, verbose=0)
# 进行分类
class_label, bbox = classify_and_regress(features)
# 显示结果
show_result(resized_proposal, class_label, bbox, i)
except Exception as e:
print(f"错误: {e}")
print("详细错误信息:")
import traceback
traceback.print_exc()
可以在当前目录显示10个图片,具体意思还要再研究一下
下面是kimi给的修改参考
你这段程序在树莓派 Ubuntu 上运行时,结果直接打印在终端里,也就是你运行脚本的命令行界面。
你看到的:
复制
模型加载成功
无法加载图像,请检查文件路径
开始提取候选区域...
找到 100 个候选区域
处理区域 1/10
类别: velvet, 边界框: [0, 0, 224, 224]
...
就是最终“结果”——没有图形界面、没有弹窗、没有保存文件,只是终端标准输出(stdout)。
(无需显示器,适合树莓派纯终端)
在
show_result() 里加上画图和保存:
Python
复制
def show_result(proposal, class_label, bbox, idx):
print(f"处理区域 {idx}: 类别: {class_label}, 边界框: {bbox}")
# 画框
x1, y1, x2, y2 = bbox
cv2.rectangle(proposal, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(proposal, class_label, (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
out_file = f"result_{idx}.jpg"
cv2.imwrite(out_file, proposal)
print(f" 结果已保存为 {out_file}")
调用处改成:
Python
复制
show_result(resized_proposal, class_label, bbox, i)
运行完后,会在当前目录下生成
result_0.jpg …
result_9.jpg,
scp 回电脑即可查看。
(需要接显示器或 VNC)
Python
复制
def show_result(proposal, class_label, bbox, idx):
print(f"处理区域 {idx}: 类别: {class_label}, 边界框: {bbox}")
x1, y1, x2, y2 = bbox
cv2.rectangle(proposal, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(proposal, class_label, (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.imshow(f"region {idx}", proposal)
cv2.waitKey(0) # 按任意键继续
cv2.destroyAllWindows()
注意:在纯 SSH 终端里运行会报错
Cannot open display,必须进入桌面环境。
(最简单,不依赖图形)
Python
复制
with open("result.txt", "w") as f:
for i, proposal_rect in enumerate(region_proposals[:max_proposals]):
...
line = f"区域{i}: {class_label} {bbox}
"
f.write(line)
因为没有显示器,首选方案 1:
把框画好并保存成 jpg,事后用
scp 或
rsync 传回电脑看图:
bash
复制
scp pi@<pi-ip>:~/your_dir/result_*.jpg ~/Desktop/
表格
复制
| 方式 | 是否需要显示器 | 结果位置 | 备注 |
|---|---|---|---|
| 终端打印 | 否 | 当前终端 | 已能看到文字 |
| 保存图片 | 否 | 当前目录
result_*.jpg | 推荐 |
| 弹窗显示 | 是 | 桌面窗口 | 需接屏或 VNC |
| 写入 txt | 否 |
result.txt | 最省资源 |
按需要挑一种即可。