import cv2
import numpy as np
import os
from PIL import Image
from skimage.feature import graycomatrix, graycoprops


def detect_fog_or_foreign_object(image_path, fog_threshold=3000, foreign_object_glcm_threshold=0.5,
                                 bright_threshold=0.2):
    # 因为cv2.imread不能处理带中文的路径,所以这里要做一些处理
    # 以字节形式读取文件内容
    img_bytes = np.fromfile(image_path, dtype=np.uint8)
    # 解码图像
    image = cv2.imdecode(img_bytes, -1)
    if image is None:
        print(f"无法读取图像: {image_path},请检查路径。")
        return "无法读取"

    # 获取图像的高度和宽度
    height, width = image.shape[:2]
    total_pixels = height * width

    # 将图像转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 使用拉普拉斯算子计算图像的清晰度
    laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()

    # 强光检测
    high_brightness_pixels = np.sum(gray > 220)  # 假设灰度值大于 220 为高亮度像素
    brightness_ratio = high_brightness_pixels / total_pixels

    # 计算灰度共生矩阵
    distances = [1]
    angles = [0]
    glcm = graycomatrix(gray, distances, angles, levels=256, symmetric=True, normed=True)

    # 提取纹理特征
    contrast = graycoprops(glcm, 'contrast')[0, 0]
    energy = graycoprops(glcm, 'energy')[0, 0]

    # 综合纹理特征判断异物
    texture_feature = (contrast + energy) / 2

    result = ""

    if brightness_ratio > bright_threshold:
        result += "强光  "
    # 根据纹理特征判断是否存在异物
    if texture_feature > foreign_object_glcm_threshold:
        result += "异物  "
    # 根据清晰度判断是否存在水雾
    if laplacian_var < fog_threshold:
        result += "水雾  "

    if result == "":
        result = "正常"

    print(
        f"图片路径:{image_path}  检测结果: {result} brightness_ratio={brightness_ratio} texture_feature={texture_feature}  laplacian_var={laplacian_var}")
    return result


if __name__ == "__main__":
    input_folder = r"D:\pj\photodetector\source_photo"  # 输入文件夹路径
    output_file = "图片检测结果.txt"

    with open(output_file, 'w', encoding='utf-8') as f:
        for root, dirs, files in os.walk(input_folder):
            for file in files:
                image_path = os.path.join(root, file)
                try:
                    img = Image.open(image_path)
                    image_format = img.format
                except Exception as e:
                    image_format = f"获取失败: {e}"

                result = detect_fog_or_foreign_object(image_path, 3000, 200, 0.1)
                f.write(f"图片路径: {image_path}\n")
                f.write(f"图片格式: {image_format}\n")
                f.write(f"检测结果: {result}\n")
                f.write("-" * 50 + "\n")

    print(f"检测结果已保存到 {output_file}")

代码重发,修改了之前的代码,异物不能用亮度分析,因为有不亮也不暗的,需要用纹理分析,灰度共生矩阵可以解决这个识别异物的问题。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐