python3 opencv 獲取圖片模糊度
阿新 • • 發佈:2021-08-20
不論你在什麼時候開始,重要的是開始之後就不要停止。 不論你在什麼時候結束,重要的是結束之後就不要悔恨。#! /usr/bin/env python # -*- coding: utf-8 -*-# # ------------------------------------------------------------------------------- # Name: 圖片模糊度計算 # Author: yunhgu # Date: 2021/8/20 11:01 # Description: # ------------------------------------------------------------------------------- import shutil from traceback import format_exc import cv2 from pathlib import Path from PIL import Image import numpy as np def ImageToMatrix(file): # 讀取圖片 im = Image.open(file) # 顯示圖片 # im.show() width, height = im.size im = im.convert("L") data = im.getdata() data = np.matrix(data, dtype='float') / 255.0 new_data = np.reshape(data, (height, width)) return new_data def Brenner(img): x, y = img.shape D = 0 for i in range(x - 2): for j in range(y - 2): D += (img[i + 2, j] - img[i, j]) ** 2 return D def variance_of_laplacian(image): return cv2.Laplacian(image, cv2.CV_64F).var() def main(input_path, output_path): for file in Path(input_path).rglob("*.jpg"): # 拉普拉斯運算元 image = cv2.imdecode(np.fromfile(file, dtype=np.uint8), cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) fm = variance_of_laplacian(gray) # Brenner 檢測 frame = ImageToMatrix(file) score = Brenner(frame) print(fm, score) # result = Path(output_path).joinpath("no_clear") # if fm >= 90: # result = Path(output_path).joinpath("90") # elif fm >= 80: # result = Path(output_path).joinpath("80") # elif fm >= 70: # result = Path(output_path).joinpath("70") # elif fm >= 60: # result = Path(output_path).joinpath("60") # elif fm >= 50: # result = Path(output_path).joinpath("50") # elif fm >= 40: # result = Path(output_path).joinpath("40") # elif fm >= 30: # result = Path(output_path).joinpath("30") # elif fm >= 20: # result = Path(output_path).joinpath("20") # elif fm >= 10: # result = Path(output_path).joinpath("10") # # result.mkdir(parents=True, exist_ok=True) # shutil.copy(file, result) if __name__ == '__main__': print("Start...") # input_Folder = input("請輸入原始檔夾:") # output_Folder = input("請輸入結果資料夾:") input_Folder = r"F:\pythonProject\圖片模糊度計算\color" output_Folder = r"F:\pythonProject\圖片模糊度計算\result" try: main(input_Folder, output_Folder) print("finished") except Exception as err: print(f"程式執行失敗!!!請聯絡資料處理中心:{err}") print(format_exc()) input("按任意鍵盤退出!!!")