前言
在圖像處理中,避免不了會碰到一些失焦模糊的圖像,特別在讀取和初始化攝像頭的時候,對失焦模糊判斷是避免不了的一步,那麼如何使用opencv去判斷一張圖像是否模糊呢?
判斷是否失焦
失焦的圖片和對焦準確的圖片最大的區別就是正常圖片輪廓明顯,而失焦圖片幾乎沒有較大像素值之間的變化,對圖像的橫向,以及縱向,分別做差分,累計差分可以用來作爲判斷是否失焦的參考。
代碼
//簡單設定閾值判斷是否失焦
bool focusDetect(Mat& img){
clock_t start, end;
start = clock();
int diff = 0;
int diff_thre = 20;
int diff_sum_thre = 1000;
for (int i = img.rows / 10; i < img.rows; i += img.rows / 10){
uchar* ptrow = img.ptr<uchar>(i);
for (int j = 0; j < img.cols - 1; j++){
if (abs(ptrow[j + 1] - ptrow[j])>diff_thre)
diff += abs(ptrow[j + 1] - ptrow[j]);
}
cout << diff << endl;
}
end = clock();
cout << "time=" << end - start << endl;
bool res = true;
if (diff < diff_sum_thre) {
cout << "the focus might be wrong!" << endl;
res = false;
}
return res;
}
//返回一個與焦距是否對焦成功的一個比例因子
double focus_measure_GRAT(Mat Image)
{
double threshold = 0;
double temp = 0;
double totalsum = 0;
int totalnum = 0;
for (int i=0; i<Image.rows; i++)
{
uchar* Image_ptr = Image.ptr<uchar>(i);
uchar* Image_ptr_1 = Image.ptr<uchar>(i+1);
for (int j=0; j<Image.cols; j++)
{
temp = max(abs(Image_ptr_1[j]-Image_ptr[j]), abs(Image_ptr[j+1]-Image_ptr[j]));
totalsum += temp;
totalnum += 1;
}
}
double FM = totalsum/totalnum;
return FM;
}