正文

python脚本之如何按照清晰度对图片进行分类(python图像清晰)快来看

文章摘要

该代码用于从目标文件夹中提取图片并根据清晰度将图片分类到两个文件夹中。代码首先定义了一个`getImageVar`函数,用于计算图片清晰度。该函数通过使用3x3拉普拉斯算子对图片进行卷积操作,计算方差以评估清晰度。接着,`get_all_file`函数用于读取文件夹中的所有文件名。代码通过用户输入设置清晰度阈值,并根据计算结果将图片分类到`vage`或`clear`文件夹中。

import os import cv2 import shutil # 计算图片清晰度 def getImageVar(img): res=0 for i in cv2.split(img): # 对图片用 3×3 拉普拉斯算子做卷积得到边缘 计算出方差,并最后返回。 # 函数求完导数后会有负值,还有会大于255的值。而原图像是uint8,即8位无符号数,所以建立的图像位数不够,会有截断。因此要使用64位有符号的数据类型,即 cv2.CV_64F。 # 再用var函数求方差 res+=cv2.Laplacian(i, cv2.CV_64F).var() return res/3 # 读取某个文件夹下面的所有文件名 返回list def get_all_file(path): all_file=[] for i in os.listdir(path): file_name=os.path.join(path,i) all_file.append(file_name) return all_file input_path=input(“请输出目标文件夹:”) threshold=int(input(“请输入清晰度阈值:”)) orign_path=os.path.join(os.path.abspath(‘.’),’img’) resoure_file_path=os.path.join(orign_path, input_path) # 图片所在文件夹 vage_file_path=os.path.join(orign_path,’vague’) clear_file_path=os.path.join(orign_path,’clear’) if not os.path.exists(vage_file_path): os.mkdir(vage_file_path) if not os.path.exists(clear_file_path): os.mkdir(clear_file_path) all_img_path=get_all_file(resoure_file_path) for img_path in all_img_path: img_name=img_path.split(‘\\’)[-1] dst=os.path.join(vage_file_path,img_name) if getImageVar(cv2.imread(img_path))>threshold: dst=os.path.join(clear_file_path, img_name) shutil.copyfile(img_path, dst)