python 判断图片会不会模糊
展开阅读全文

python 判断图片会不会模糊

判断图片是否模糊可以通过多种方法实现,常见的方法包括分析图像的频率域特性、计算图像的锐利度或者使用预训练的神经网络模型进行模糊检测。以下是几种常见的 Python 实现方法:

方法一:使用Laplacian方差 Laplacian方差是一种简单且有效的模糊检测方法。基本原理是计算图像的Laplacian变换,然后计算变换结果的方差。方差越小,图像越模糊。

import cv2
import numpy as np

def is_blurry(image_path, threshold=100):
    # 读取图像
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    
    # 计算Laplacian变换
    laplacian_var = cv2.Laplacian(image, cv2.CV_64F).var()
    
    # 判断是否模糊
    if laplacian_var < threshold:
        return True
    else:
        return False

# 示例使用
image_path = 'path_to_your_image.jpg'
if is_blurry(image_path):
    print("The image is blurry.")
else:
    print("The image is sharp.")

方法二:使用频域分析

可以通过将图像转换到频域(例如使用FFT),然后分析高频成分的数量来判断图像是否模糊。

import cv2
import numpy as np

def is_blurry_fft(image_path, threshold=0.05):
    # 读取图像
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    
    # 计算FFT
    f = np.fft.fft2(image)
    fshift = np.fft.fftshift(f)
    
    # 计算高频成分比例
    rows, cols = image.shape
    crow, ccol = rows // 2 , cols // 2
    radius = 30  # 定义高频成分的半径
    high_freq_mask = np.zeros((rows, cols), np.uint8)
    cv2.circle(high_freq_mask, (ccol, crow), radius, 1, -1)
    high_freq = np.abs(fshift * high_freq_mask)
    high_freq_sum = np.sum(high_freq)
    total_sum = np.sum(np.abs(fshift))
    high_freq_ratio = high_freq_sum / total_sum
    
    # 判断是否模糊
    if high_freq_ratio < threshold:
        return True
    else:
        return False

# 示例使用
image_path = 'path_to_your_image.jpg'
if is_blurry_fft(image_path):
    print("The image is blurry.")
else:
    print("The image is sharp.")