image_blur_detection.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Created by 阳坤 on 2022/2/23.
  3. //
  4. #include "image_blur_detection.h"
  5. int image_blur_detection(const char *filename) {
  6. const char *temp_image_url = filename;
  7. cv::Mat cvImage = cv::imread(temp_image_url);
  8. return doDetection(cvImage);
  9. }
  10. int bytes_blur_detection(uint8_t *pData, int len) {
  11. cv::Mat img;
  12. std::vector<uchar> data;
  13. for (int i = 0; i < len; ++i) {
  14. data.push_back(pData[i]);
  15. }
  16. img = cv::imdecode(data, cv::IMREAD_COLOR);
  17. cv::flip(img, img, -1);
  18. img.channels();
  19. return doDetection(img);
  20. }
  21. int doDetection(cv::Mat cvImage) {
  22. //如果读入图像失败
  23. if (cvImage.empty()) {
  24. return -1;
  25. } else {
  26. cv::Mat grayCVImage;
  27. cv::cvtColor(cvImage, grayCVImage, cv::COLOR_BGR2GRAY);
  28. if (!grayCVImage.empty()) {
  29. cv::Mat laplacianImage;
  30. cv::Laplacian(grayCVImage, laplacianImage, CV_64F);
  31. cv::Scalar mu, sigma;
  32. cv::meanStdDev(laplacianImage, mu, sigma);
  33. int blur_value = sigma.val[0] * sigma.val[0];
  34. blur_value = blur_value < 100 ? image_color_ratio(grayCVImage) : blur_value;
  35. cvImage.release();
  36. grayCVImage.release();
  37. return blur_value;
  38. }
  39. }
  40. return -1;
  41. }
  42. //定义比较的函数
  43. static bool cmp_value(const std::pair<long, long> left, const std::pair<long, long> right) {
  44. return left.second < right.second;
  45. }
  46. int image_color_ratio(cv::Mat image) {
  47. int num = 0;//记录颜色的像素点
  48. std::map<long, long> colors;
  49. for (int i = 0; i < image.rows; ++i) {
  50. for (int j = 0; j < image.cols; ++j) {
  51. int gray_data = image.at<uchar>(i, j);
  52. if (colors.count(gray_data) == 0) {
  53. colors[gray_data] = 1;
  54. } else {
  55. long a = ++colors[gray_data];
  56. colors[gray_data] = a;
  57. }
  58. }
  59. }
  60. if (!colors.empty()) {
  61. auto maxCount = 0L;
  62. if (colors.size() > 1) {
  63. maxCount = max_element(colors.begin(), colors.end(), cmp_value)->second;
  64. } else {
  65. std::map<long, long>::iterator iter;
  66. iter = colors.begin();
  67. while (iter != colors.end()) {
  68. maxCount = iter->second;
  69. break;
  70. }
  71. }
  72. float i = maxCount * 1.0f / (image.rows * image.cols);
  73. if (i >= DEFAULT_PIX_THRESHOLD) {
  74. num = DEFAULT_BLUR_THRESHOLD + 1;
  75. };
  76. }
  77. return num;
  78. }