2025-06-14【视觉】批量筛选图集中包含某种物体对象的方法

发布于:2025-06-15 ⋅ 阅读:(18) ⋅ 点赞:(0)

在这里插入图片描述
要查找包含的图片
在这里插入图片描述
查找结果如下:
在这里插入图片描述
其中有一个是错误的。

代码

#
#
# import aircv as ac
#
# # 读取图像
# im_source = ac.imread('large.jpg')
# im_search = ac.imread('s.jpg')
# # 查找模板
# result = ac.find_template(im_source, im_search)
# print(result)

import cv2
import numpy as np
import os
from PIL import Image
import cv2

def imread_chinese(filepath):
    """支持中文路径的图像读取函数"""
    image = Image.open(filepath).convert('RGB')  # 读取图像并转为RGB
    return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)  # 转为OpenCV格式

def find_template_in_image(big_img, small_img):
    """
    使用 ORB 算法判断 big_img 是否包含 small_img。
    """
    orb = cv2.ORB_create()
    kp1, des1 = orb.detectAndCompute(small_img, None)
    kp2, des2 = orb.detectAndCompute(big_img, None)

    if des1 is None or des2 is None:
        return False  # 没有提取到特征描述符

    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
    matches = bf.match(des1, des2)
    matches = sorted(matches, key=lambda x: x.distance)

    good_matches = [m for m in matches[:10] if m.distance < 50]  # 可调参数

    return len(good_matches) > 2  # 设定阈值


def find_images_containing_template(image_folder, template_path, output_folder="matched"):
    """
    遍历文件夹,筛选出包含模板的小图,并保存结果。
    """
    small_img = cv2.imread(template_path)
    assert small_img is not None, "无法加载模板图像"

    matched_images = []

    for filename in os.listdir(image_folder):
        file_path = os.path.join(image_folder, filename)
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            big_img = imread_chinese(file_path)
            if big_img is None:
                print(f"无法加载图像(可能损坏):{filename}")
                continue


            print(f"正在处理:{filename}")
            if find_template_in_image(big_img, small_img):
                print(f"✅ 找到匹配:{filename}")
                matched_images.append(filename)

                # 可选:保存匹配成功的图像到指定目录
                if not os.path.exists(output_folder):
                    os.makedirs(output_folder)
                cv2.imwrite(os.path.join(output_folder, filename), big_img)

    return matched_images


# 示例调用
image_folder = 'images'          # 大图所在文件夹
template_path = 'small.jpg'     # 小图模板路径
output_list = find_images_containing_template(image_folder, template_path)

print("包含模板的图片列表:")
for img_name in output_list:
    print(img_name)


网站公告

今日签到

点亮在社区的每一天
去签到