原理:先对图像用拉普拉斯算子进行滤波,然后求取得到的结果图像的方差,如果方差小于一定值则图片视为模糊。
1.python 版
import os import cv2 img_path = r".images" good_img_path = r".good" bad_img_path = r".bad" Threshold = 50 for filename in os.listdir(img_path): filepath = os.path.join(img_path, filename) frame = cv2.imread(filepath) img2gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 将图片压缩为单通道的灰度图 score = cv2.Laplacian(img2gray, cv2.CV_64F).var() cv2.putText(frame, str(score), (123, 456), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3) if score < Threshold: path = os.path.join(bad_img_path, filename) if not os.path.exists(bad_img_path): os.makedirs(bad_img_path) cv2.imwrite(path, frame) else: path = os.path.join(good_img_path, filename) if not os.path.exists(good_img_path): os.makedirs(good_img_path) cv2.imwrite(path, frame)
123456789101112131415161718192021222.c++版
#include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace std; using namespace cv; int blurryConf = 50; //default bool isImageBlurry(cv::Mat& img) { cv::Mat matImageGray; // converting image's color space (RGB) to grayscale cv::cvtColor(img, matImageGray, CV_BGR2GRAY); cv::Mat dst, abs_dst; cv::Laplacian(matImageGray, dst, CV_16S); cv::convertScaleAbs( dst, abs_dst ); cv::Mat tmp_m, tmp_sd; double m , sd; cv::meanStdDev(dst, tmp_m, tmp_sd); m = tmp_m.at<double>(); sd = tmp_sd.at<double>(); std::cout << "img score : " << sd * sd << std::endl; return ((sd * sd) <= blurryConf); //true : 1 ;false : 0 } int main() {Mat img = imread("./test.jpg");if(isImageBlurry(img)){cout << " img is blurry !! " << endl;}else{cout << " img is not blurry !! " << endl;}return 0; }
123456789101112131415161718192021222324252627282930313233343536373839