模板匹配能搭配滤波处理和边缘检测吗,为什么我在多模板匹配里面加了中值滤波处理后运行没问题,但不进行模板匹配了
import time, sensor, image
from image import SEARCH_EX, SEARCH_DS
# 初始化传感器和设置
sensor.reset()
sensor.set_contrast(1)
sensor.set_gainceiling(16)
sensor.set_framesize(sensor.QQVGA)
sensor.set_pixformat(sensor.GRAYSCALE)
# 模板列表
templates = [
"/0.pgm", "/1.pgm", "/2.pgm", "/3.pgm", "/4.pgm",
]
# ROI列表
roi_list = [(10, 0, 40, 40)] * len(templates)
sensor.skip_frames(time = 2000) # 让新的设置生效
clock = time.clock() # 跟踪FPS帧率
while(True):
clock.tick() # 追踪两个snapshots()之间经过的毫秒数.
img = sensor.snapshot() # 拍一张照片,返回图像
# 第一个参数是内核大小。N对应于((N * 2)+1)^ 2内核大小。
# 例如。 1 == 3x3内核,2 == 5x5内核等。
# 第二个参数“percentile”是从NxN邻域中选择的百分位数。
# 0.5是中位数,0.25是下四分位数,0.75是上四分位数。
img.median(1, percentile=0.5, threshold=True, offset=5, invert=True)
# 添加中值滤波预处理
def apply_median_blur(image, kernel_size=3):
return image.median_blur(kernel_size)
clock = time.clock()
while True:
clock.tick()
# 捕获图像
img = sensor.snapshot()
# 对图像进行中值滤波预处理
img = apply_median_blur(img)
char_positions = [] # 存储字符及其位置
for t, roi in zip(templates, roi_list):
template = image.Image(t)
r = img.find_template(template, 0.70, step=3, search=SEARCH_DS, roi=roi)
if r:
img.draw_rectangle(r)
char_positions.append((t[1], r[0])) # 使用模板文件名的第一个字符作为字符标识
# 检查是否有至少三个字符被识别
if len(char_positions) > 2:
# 按水平位置排序
char_positions.sort(key=lambda x: x[1])
# 将排序后的字符打印出来
result = ''.join([char for char, _ in char_positions])
print("识别结果:", result)