关于OpenMV Cam在采集800×600分辨率图像时的实现方式,这是一个很好的技术问题。
OpenMV Cam处理不同分辨率图像的方式主要取决于具体的硬件型号和配置:
这个缩放的话,对图像质量有什么影响吗?
我利用OpenMV4 H7 Plus平台,采用的是ov5640摄像头,我设置的是采集800*600的图像,这个图像是通过裁剪得到的还是压缩原始图像得到的?
如果是压缩图像的话是怎么压缩的?对图像质量有什么影响吗?
程序里边采集的灰度图像是OV5640采集的彩色图像然后经过STM32内部算法转化得到的吧?
OV5640无法直接输出灰度图?
import sensor
import time
import math
from pyb import UART
# ==================== 初始化设置 ====================
print("=== OpenMV硬币识别系统启动 ===")
print("初始化摄像头...")
# 摄像头设置
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_auto_gain(False) # 关闭自动增益,保证颜色稳定性
sensor.set_auto_whitebal(False) # 关闭自动白平衡
sensor.skip_frames(time=2000)
print("摄像头初始化完成")
# 串口初始化
try:
uart = UART(3, 115200)
uart.init(115200, bits=8, parity=None, stop=1, timeout_char=1000)
print("串口初始化完成")
except:
print("串口初始化失败")
# ==================== 硬币参数配置 ====================
# 优化重点:调整颜色阈值,尤其是5角硬币的黄铜色识别
# 采用LAB颜色空间:L(亮度), A(绿-红), B(蓝-黄)
COIN_PARAMS = {
"1_jiao": {
# 1角:银白色,亮度较高,颜色偏冷
"color_threshold": (60, 100, -15, 5, -15, 5), # L偏高,A偏绿,B偏蓝
"radius_range": (18, 25),
"value": 0.1,
"display_color": (255, 255, 0),
"name": "1角"
},
"5_jiao": {
# 5角:黄铜色,重点优化,适应新旧硬币
# 旧硬币可能偏暗(L低),新硬币偏亮(L高),但都保持红黄色调(A正,B正)
"color_threshold": (30, 90, 5, 45, 10, 50), # A偏红,B偏黄,L范围放宽
"radius_range": (20, 28),
"value": 0.5,
"display_color": (0, 255, 255),
"name": "5角"
},
"1_yuan": {
# 1元:银白色,亮度中等,颜色偏中性
"color_threshold": (50, 90, -10, 10, -10, 10), # L中等,A和B接近中性
"radius_range": (25, 35),
"value": 1.0,
"display_color": (0, 255, 0),
"name": "1元"
}
}
# ==================== 全局变量 ====================
coin_counts = {"1_jiao": 0, "5_jiao": 0, "1_yuan": 0}
total_value = 0.0
frame_count = 0
send_interval = 15
last_sent_value = 0.0
# ==================== 核心功能函数 ====================
def distance_between_circles(circle1, circle2):
"""计算两个圆心之间的距离"""
dx = circle1.x() - circle2.x()
dy = circle1.y() - circle2.y()
return math.sqrt(dx*dx + dy*dy)
def is_overlapping(circle1, circle2, overlap_threshold=0.7):
"""检查两个圆是否重叠"""
distance = distance_between_circles(circle1, circle2)
min_distance = (circle1.r() + circle2.r()) * overlap_threshold
return distance < min_distance
def filter_overlapping_circles(circles):
"""过滤重叠的圆形"""
if not circles:
return []
# 按半径排序(大的先保留)
circles_sorted = sorted(circles, key=lambda c: c.r(), reverse=True)
filtered = []
for circle in circles_sorted:
overlap = False
for kept_circle in filtered:
if is_overlapping(circle, kept_circle):
overlap = True
break
if not overlap:
filtered.append(circle)
return filtered
def classify_coin(radius, img, center_x, center_y):
"""优化:先颜色识别,再大小筛选"""
# 在圆心区域采样颜色(扩大采样区域提高准确性)
sample_size = 10
roi_x = max(0, center_x - sample_size//2)
roi_y = max(0, center_y - sample_size//2)
roi_w = min(sample_size, 320 - roi_x)
roi_h = min(sample_size, 240 - roi_y)
if roi_w <= 0 or roi_h <= 0:
return None
# 获取LAB颜色统计
color_stats = img.get_statistics(roi=(roi_x, roi_y, roi_w, roi_h))
l_mean = color_stats.l_mean()
a_mean = color_stats.a_mean()
b_mean = color_stats.b_mean()
# 1. 先进行颜色匹配(首要条件)
color_matches = []
for coin_type, params in COIN_PARAMS.items():
l_min, l_max, a_min, a_max, b_min, b_max = params["color_threshold"]
# 检查是否在颜色范围内
l_match = l_min <= l_mean <= l_max
a_match = a_min <= a_mean <= a_max
b_match = b_min <= b_mean <= b_max
if l_match and a_match and b_match:
# 计算颜色匹配度(0-1),用于后续排序
l_score = 1 - abs(l_mean - (l_min+l_max)/2) / (l_max - l_min)
a_score = 1 - abs(a_mean - (a_min+a_max)/2) / (a_max - a_min)
b_score = 1 - abs(b_mean - (b_min+b_max)/2) / (b_max - b_min)
color_score = (l_score + a_score + b_score) / 3
color_matches.append((coin_type, color_score))
# 没有颜色匹配的硬币直接返回
if not color_matches:
return None
# 2. 对颜色匹配的硬币进行大小筛选
for coin_type, color_score in sorted(color_matches, key=lambda x: x[1], reverse=True):
min_r, max_r = COIN_PARAMS[coin_type]["radius_range"]
if min_r <= radius <= max_r:
# 计算大小匹配度
size_score = 1 - abs(radius - (min_r+max_r)/2) / (max_r - min_r)
# 综合评分(颜色权重更高)
total_score = color_score * 0.7 + size_score * 0.3
if total_score > 0.6: # 提高阈值,减少误判
return coin_type
return None
def draw_detection_result(img, circle, coin_type):
"""在图像上绘制检测结果"""
x, y, r = circle.x(), circle.y(), circle.r()
color = COIN_PARAMS[coin_type]["display_color"]
name = COIN_PARAMS[coin_type]["name"]
img.draw_circle(x, y, r, color=color, thickness=2)
img.draw_cross(x, y, color=color, size=6, thickness=1)
text = "{} R:{}".format(name, r)
text_x = max(0, x - len(text)*3)
text_y = max(15, y - r - 15)
img.draw_rectangle(text_x-2, text_y-2, len(text)*6+4, 12, color=(0,0,0), fill=True)
img.draw_string(text_x, text_y, text, color=color, scale=0.6)
def update_info_display(img, detected_count):
"""更新屏幕上的信息显示"""
img.draw_rectangle(0, 0, 320, 50, color=(0,0,0), fill=True)
img.draw_string(5, 2, "OpenMV多硬币识别", color=(255,255,255), scale=0.8)
stats_text = "1角:{} 5角:{} 1元:{}".format(
coin_counts["1_jiao"], coin_counts["5_jiao"], coin_counts["1_yuan"])
img.draw_string(5, 15, stats_text, color=(255,255,255), scale=0.8)
value_text = "总额: {:.2f}元".format(total_value)
img.draw_string(5, 28, value_text, color=(255,255,255), scale=0.8)
status_text = "检测到: {}个硬币".format(detected_count)
img.draw_string(5, 41, status_text, color=(255,255,255), scale=0.8)
def send_to_stm32():
"""发送数据到STM32"""
global last_sent_value
if abs(total_value - last_sent_value) > 0.01 or frame_count % 30 == 0:
data = "{},{},{},{:.2f}\n".format(
coin_counts["1_jiao"],
coin_counts["5_jiao"],
coin_counts["1_yuan"],
total_value
)
try:
uart.write(data)
last_sent_value = total_value
print("发送到STM32:", data.strip())
except:
print("串口发送失败")
def detect_coins(img):
"""检测并分类图像中的硬币"""
global coin_counts, total_value
# 重置统计
coin_counts = {"1_jiao": 0, "5_jiao": 0, "1_yuan": 0}
total_value = 0.0
# 查找圆形(优化参数提高检测稳定性)
circles = img.find_circles(
threshold=3000, # 提高阈值减少噪点
x_margin=10,
y_margin=10,
r_margin=5,
r_min=15, # 缩小最小半径范围
r_max=40,
r_step=1
)
# 过滤重叠的圆形
filtered_circles = filter_overlapping_circles(circles)
detected_coins = []
for c in filtered_circles:
# 先颜色后大小的分类逻辑
coin_type = classify_coin(c.r(), img, c.x(), c.y())
if coin_type:
detected_coins.append((c, coin_type))
coin_counts[coin_type] += 1
total_value += COIN_PARAMS[coin_type]["value"]
draw_detection_result(img, c, coin_type)
return detected_coins
# ==================== 主程序循环 ====================
def main():
global frame_count
print("开始硬币识别...")
print("=" * 40)
clock = time.clock()
while True:
clock.tick()
frame_count += 1
try:
# 捕获图像
img = sensor.snapshot()
# 检测硬币
detected_coins = detect_coins(img)
# 更新信息显示
update_info_display(img, len(detected_coins))
# 显示帧率
fps = clock.fps()
img.draw_string(250, 5, "FPS:{:.1f}".format(fps), color=(255,255,0), scale=0.7)
# 定期发送数据到STM32
if frame_count % send_interval == 0:
send_to_stm32()
# 输出检测信息
if len(detected_coins) > 0:
print("检测到 {} 个硬币 - 1角:{}个, 5角:{}个, 1元:{}个, 总计:{:.2f}元".format(
len(detected_coins), coin_counts["1_jiao"], coin_counts["5_jiao"],
coin_counts["1_yuan"], total_value))
except Exception as e:
print("处理帧时出错:", e)
# 尝试重新初始化摄像头
try:
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=1000)
print("摄像头重新初始化完成")
except:
print("摄像头重新初始化失败")
time.sleep(1000)
# ==================== 程序启动 ====================
if __name__ == "__main__":
try:
main()
except Exception as e:
print("程序错误:", e)
sensor.reset()
time.sleep(2000)
我想实现通过openmv识别硬币(一角,五角,一元),准确识别出硬币的总额。但是现在的代码不能准确识别出五角和一角的区别,且对于识别的距离要求十分苛刻。 1、我希望有更好的识别硬币的逻辑思路。 2、识别距离部分的优化,或者可以有更好的代码。 刚开始学openmv,请问以上问题如何解决。😊