image_blur_detection.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. if (blur_value < DEFAULT_BLUR_THRESHOLD) {
  35. int color = image_color_ratio(grayCVImage);
  36. blur_value = color == 0 ? blur_value : color;
  37. }
  38. cvImage.release();
  39. grayCVImage.release();
  40. return blur_value;
  41. }
  42. }
  43. return -1;
  44. }
  45. //定义比较的函数
  46. static bool cmp_value(const std::pair<long, long> left, const std::pair<long, long> right) {
  47. return left.second < right.second;
  48. }
  49. int image_color_ratio(cv::Mat image) {
  50. int num = 0;
  51. std::map<long, long> colors;
  52. for (int i = 0; i < image.rows; ++i) {
  53. for (int j = 0; j < image.cols; ++j) {
  54. int gray_data = image.at<uchar>(i, j);
  55. if (colors.count(gray_data) == 0) {
  56. colors[gray_data] = 1;
  57. } else {
  58. long a = ++colors[gray_data];
  59. colors[gray_data] = a;
  60. }
  61. }
  62. }
  63. if (!colors.empty()) {
  64. auto maxCount = 0L;
  65. if (colors.size() > 1) {
  66. maxCount = max_element(colors.begin(), colors.end(), cmp_value)->second;
  67. } else {
  68. std::map<long, long>::iterator iter;
  69. iter = colors.begin();
  70. while (iter != colors.end()) {
  71. maxCount = iter->second;
  72. break;
  73. }
  74. }
  75. float i = (float) maxCount / (float) (image.rows * image.cols);
  76. if (i >= DEFAULT_PIX_THRESHOLD) {
  77. num = DEFAULT_BLUR_THRESHOLD + 1;
  78. };
  79. }
  80. return num;
  81. }