首页 > 编程语言 >python 版本对比图片

python 版本对比图片

时间:2024-07-07 21:20:58浏览次数:10  
标签:files name similarity python results unmatched 版本 threshold 对比


import cv2
import numpy as np
import os
def calculate_black_pixels_in_sectors(image,sector):
    # 将图像转换为二值图像
    _, image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
    
    # 获取图像尺寸
    height, width = image.shape
    
    # 计算几何中心
    center_x, center_y = width // 2, height // 2

    # 定义角度间隔
    angle_step = 360 / sector

    # 存储每个扇区的黑色像素数量
    black_pixel_counts = np.zeros(sector)

    # 循环遍历36个扇区
    for i in range(sector):
        # 计算当前扇区的角度范围
        start_angle = np.deg2rad(i * angle_step)
        end_angle = np.deg2rad((i + 1) * angle_step)

        # 创建一个掩码,用于提取当前扇区内的像素
        y, x = np.ogrid[:height, :width]
        mask = ((x - center_x) * np.cos(start_angle) + (y - center_y) * np.sin(start_angle) >= 0) & \
               ((x - center_x) * np.cos(end_angle) + (y - center_y) * np.sin(end_angle) <= 0)

        # 计算当前扇区内的黑色像素数量
        black_pixel_counts[i] = np.sum(image[mask] == 0)

    return black_pixel_counts


def compare_images(image_path1, image_path2, pixel_threshold, sector_threshold,sector):
    # 读取图像并转换为灰度
    image1 = cv2.imread(image_path1, cv2.IMREAD_GRAYSCALE)
    image2 = cv2.imread(image_path2, cv2.IMREAD_GRAYSCALE)
    
    # 计算两张图像每个扇区的黑色像素数量
    black_pixels1 = calculate_black_pixels_in_sectors(image1,sector)
    black_pixels2 = calculate_black_pixels_in_sectors(image2,sector)

    # 比较两个图像的黑色像素分布
    diff = np.abs(black_pixels1 - black_pixels2)
    
    # 检查有多少个扇区的差异没有超过像素阈值
    num_similar_sectors = np.sum(diff <= pixel_threshold)
    
    # 计算相似扇区的百分比
    similarity_percentage = (num_similar_sectors / len(black_pixels1)) * 100
    
    # 检查超过像素阈值的扇区数量是否超过了数量阈值
    num_exceeding_sectors = np.sum(diff > pixel_threshold)
    is_within_sector_threshold = num_exceeding_sectors <= sector_threshold
    
    return similarity_percentage, is_within_sector_threshold

def compare_directories(dirA, dirB, pixel_threshold, sector_threshold,similarity_threshold):
    # 确保两个目录存在
    if not os.path.exists(dirA) or not os.path.exists(dirB):
        raise ValueError("One or both directories do not exist.")

    # 获取目录列表
    dirsA = os.listdir(dirA)
    dirsB = os.listdir(dirB)

    # 只保留两个目录共有的子目录名称
    common_dirs = list(set(dirsA).intersection(set(dirsB)))

    results = {}
    unmatched_files_A = {}
    unmatched_files_B = {}
    high_similarity_pairs = []

    for common_dir in common_dirs:
        pathA = os.path.join(dirA, common_dir)
        pathB = os.path.join(dirB, common_dir)

        # 获取两个子目录下的文件列表
        filesA = os.listdir(pathA)
        filesB = os.listdir(pathB)

        # 只保留两个子目录共有的文件名称
        common_files = list(set(filesA).intersection(set(filesB)))

        for file_name in common_files:
            img_path_A = os.path.join(pathA, file_name)
            img_path_B = os.path.join(pathB, file_name)

            # 调用 compare_images 函数
            similarity, within_threshold = compare_images(img_path_A, img_path_B, pixel_threshold, sector_threshold,sector)

            # 保存结果
            if common_dir not in results:
                results[common_dir] = {}
            results[common_dir][file_name] = {'similarity': similarity, 'within_threshold': within_threshold}
            # 检查相似度是否超过阈值
            if similarity >= similarity_threshold:
                high_similarity_pairs.append((img_path_A, img_path_B, similarity))
         # 统计未匹配的文件
        unmatched_files_A[common_dir] = list(set(filesA) - set(common_files))
        unmatched_files_B[common_dir] = list(set(filesB) - set(common_files))
        # 添加未匹配文件的统计结果
    results['unmatched_files_A'] = unmatched_files_A
    results['unmatched_files_B'] = unmatched_files_B
        # 将高相似度的图片对路径添加到结果中
    results['high_similarity_pairs'] = high_similarity_pairs
    return results

# # 使用函数
# image_path1 = r'imgB/01_1.jpg'
# image_path2 = r'imgB/03_3.jpg'
# pixel_threshold = 100  # 单个扇区像素差异阈值
# sector_threshold = 5   # 超过像素差异阈值的扇区数量阈值

# similarity, within_threshold = compare_images(image_path1, image_path2, pixel_threshold, sector_threshold)

# if within_threshold:
#     print(f"Images are {similarity:.2f}% similar in their black pixel distribution and the number of exceeding sectors is within the threshold.")
# else:
#     print(f"Images are {similarity:.2f}% similar in their black pixel distribution but the number of exceeding sectors exceeds the threshold.")



# 使用函数
dirA = 'imgA'
dirB = 'imgB'
pixel_threshold = 50
sector_threshold = 5
sector=72
similarity_threshold = 70
# 使用函数
results = compare_directories(dirA, dirB, pixel_threshold, sector_threshold,similarity_threshold)
# 输出结果
for dir_name, files in results.items():
    # 如果当前项是字典类型并且不是unmatched_files_A或unmatched_files_B
    if isinstance(files, dict) and dir_name not in ('unmatched_files_A', 'unmatched_files_B'):
        print(f"Directory: {dir_name}")
        for file_name, info in files.items():
            print(f"  File: {file_name}, Similarity: {info['similarity']:.2f}%, Within Threshold: {info['within_threshold']}")

# 输出未匹配的文件
if 'unmatched_files_A' in results:
    print("\nUnmatched files in imgA:")
    for dir_name, files in results['unmatched_files_A'].items():
        print(f"  Directory: {dir_name}")
        for file_name in files:
            print(f"    File: {file_name}")

if 'unmatched_files_B' in results:
    print("\nUnmatched files in imgB:")
    for dir_name, files in results['unmatched_files_B'].items():
        print(f"  Directory: {dir_name}")
        for file_name in files:
            print(f"    File: {file_name}")

# 输出高相似度的图片对
if 'high_similarity_pairs' in results:
    print("\nHigh Similarity Pairs:")
    for imgA, imgB, sim in results['high_similarity_pairs']:
        print(f"  Pair: {os.path.basename(imgA)} and {os.path.basename(imgB)}, Similarity: {sim}%")

标签:files,name,similarity,python,results,unmatched,版本,threshold,对比
From: https://www.cnblogs.com/DINGJINXING/p/18288933

相关文章

  • C++ 版本 对比字符图片
    #include<iostream>#include<opencv2/opencv.hpp>#include<map>#include<vector>#include<string>#include<set>#include<filesystem>namespacefs=std::filesystem;//计算图像中每个扇区的黑色像素数量voidcalculateBlackPi......
  • 数学建模——层次分析法 AHP(Python代码)
    层次分析法    层次分析法是由美国运筹学家、匹兹堡大学教授T.L.Saaty于20世纪70年代创立的一种系统分析与决策的综合评价方法,是在充分研究了人类思维过程的基础上提出来的,它较合理地解决了定性问题定量化的处理过程。    AHP的主要特点是通过建立递阶层次结......
  • 数学建模——Topsis法(Python代码)
    Topsis法    Topsis法是一种常用的综合评价方法,能充分利用原始数据的信息,其结果能精确反映各评价方案之间的差距。该方法对数据分布及样本含量没有严格限制,数据计算简单易行。    基本过程为先将原始数据矩阵统一指标类型(一般正向化处理)得到正向化的矩阵,再对......
  • python 调用 bat,传入参数,bat中实现如果有参数传入则读取参数,没有的话就使用内部的变量
    以下是一个Python调用BAT脚本并向其传递参数的示例,同时BAT脚本中会判断是否有参数传入并进行相应处理:Python代码:pythonimportsubprocess#定义要传递的参数parameter="example_parameter"#调用BAT脚本并传递参数subprocess.run(["your_bat_script.b......
  • Python极简美学:用一行代码完成的26个日常任务!
    Python以其简洁优雅著称,能够用最少的代码行数实现强大的功能。本文特别为Python初学者设计,旨在展示Python如何以一行代码解决常见的编程任务,让你体验Python的极简美学。通过这些实例,你不仅能够学习到Python的基础知识,还能掌握一些高效编码的小技巧。1.计算列表平均值number......
  • Python和MATLAB微机电健康推导算法和系统模拟优化设计
    ......
  • 基于Python实现的博客内容推荐系统
    前言大家好!今天来给大家分享一个基于Python实现的博客内容推荐系统。这个项目源自于一个想法:如何为博客用户提供他们最感兴趣的内容。正如大家所知道的,内容推荐系统在电商、视频平台和社交媒体中应用广泛,能显著提升用户体验和平台粘性。那么,如何为我们的博客(比如你自己的W......
  • Python算法模版:图论中的最小生成树算法
        最小生成树具有什么特性,相信学过相关知识的同学知道(没学过的可以自己了解一下),就是说最小生成树的边权值之和最小,相对应的其最大边权也是最小的,适合解决n个城市,m条边,然后叫你求最小划分路径是什么样的。Kruskal算法模版    首先,肯定要对题目所给的数据进......
  • python函数和c的区别有哪些
    Python有很多内置函数(buildinfunction),不需要写头文件,Python还有很多强大的模块,需要时导入便可。C语言在这一点上远不及Python,大多时候都需要自己手动实现。C语言中的函数,有着严格的顺序限制,如果要调用函数,该函数需要在本次调用之前就需要被实现,或者在程序开头事先声明,而Py......
  • python如何查看内置函数
    如何通过命令查看python中的所有内置函数和内置常量举例python版本:利用python中的语句输出python中的所有内置函数及内置常量名:dir(__builtin__)输出一个列表:In [1]: dir(__builtin__)Out[1]:['ArithmeticError','AssertionError','AttributeError','BaseEx......