【OpenCV】python OpenCV 分析影像模糊程度 檢測圖片模糊 blur sample code (內含範例程式碼)

前言

這支程式可以幫助我們分析一張影像的模糊程度。

sample code

import cv2
import glob
import os
import shutil

folder_path = glob.glob("./input_folder/*.png")
output_folder = "./output_folder"

BIG_BLUR_THESHOLD = 300
MID_BLUR_THESHOLD = 200
SMALL_BLUR_THESHOLD = 100

score_dist = {}


def copyimgfile(text, img_path, fm, output_f):
    print(f"[{text}] img = {img_path}, blur_score = {fm}")
    src = img_path
    dst = output_f + img_path.split("/")[-1]
    print(f"[copyfile] to {dst}")
    shutil.copyfile(src, dst)

def variance_of_laplacian(image):
    '''
    1.calculate laplacian of the images 
    2.calculate variance
    '''
    return cv2.Laplacian(image, cv2.CV_64F).var()


if __name__ == '__main__':
    total_num = len(folder_path)
    for img_path in folder_path:
        # read image
        image = cv2.imread(img_path)

        # convert to grayscale images
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 1.calculate laplacian of the images 
        # 2.calculate variance
        fm = int(variance_of_laplacian(gray))

        score_rank = int(fm/100)

        if(score_dist.get(score_rank)):
            score_dist[score_rank] += 1
        else:
            score_dist[score_rank] = 1

        # rename files with score (if needed)
        # src = img_path
        # basename = os.path.basename(img_path)
        # new_basename = f"s{fm}-{basename}"
        # new_basename = basename.replace(".png", f"-s{fm}.png")

        # dst = src.replace(basename, new_basename)
        # print(src)
        # print(dst)
        # os.rename(src, dst)

        # process result
        if fm > BIG_BLUR_THESHOLD:
            text = "Very Very Very Not Blurry"
            copyimgfile(text, img_path, fm, output_folder+f"/{BIG_BLUR_THESHOLD}/")
        elif fm > MID_BLUR_THESHOLD:
            text = "Very Very Not Blurry"
            copyimgfile(text, img_path, fm, output_folder+f"/{MID_BLUR_THESHOLD}/")
        elif fm > SMALL_BLUR_THESHOLD:
            text = "Very Not Blurry"
            copyimgfile(text, img_path, fm, output_folder+f"/{SMALL_BLUR_THESHOLD}/") 
        else:
            text = "Not Blurry"

    k = sorted(score_dist.keys())
    for key in k:
        print(f"{key}: {score_dist[key]}\t{score_dist[key]/total}%")

Reference

https://blog.csdn.net/WZZ18191171661/article/details/96602043