utils.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <iostream>
  2. #include <opencv2/opencv.hpp>
  3. using namespace cv;
  4. using namespace std;
  5. int applyMask(unsigned short* input, unsigned char* pmask, int Width, int Height, unsigned short* output)
  6. {
  7. if (input == nullptr)
  8. {
  9. return 0;
  10. }
  11. if (pmask == nullptr)
  12. {
  13. return 0;
  14. }
  15. Mat src(Size(Width, Height), CV_16U, input);
  16. Mat mask(Size(Width, Height), CV_8U, pmask);
  17. Mat result;
  18. bitwise_and(src, src, result, mask);
  19. if (result.empty() || result.rows != Height || result.cols != Width )
  20. {
  21. return 0;
  22. }
  23. memcpy(output, result.data, Width * Height * sizeof(unsigned short));
  24. return 1;
  25. }
  26. int getMaskRect(unsigned char* pmask, int Width, int Height, int &x,int &y,int &RectWidth,int &RectHeight)
  27. {
  28. if (pmask == nullptr)
  29. {
  30. return 0;
  31. }
  32. Mat mask(Size(Width, Height), CV_8U, pmask);
  33. if (!sum(mask)[0])
  34. {
  35. return 0;
  36. }
  37. cv::Mat nonZeroPoints;
  38. cv::findNonZero(mask, nonZeroPoints);
  39. cv::Rect rect = cv::boundingRect(nonZeroPoints);
  40. x = rect.x;
  41. y = rect.y;
  42. RectWidth = rect.width;
  43. RectHeight = rect.height;
  44. return 1;
  45. }
  46. int cropImg(unsigned short *input, unsigned short *output, int Width, int Height, int x, int y, int RectWidth, int RectHeight)
  47. {
  48. if (input == nullptr)
  49. {
  50. return 0;
  51. }
  52. if (output == nullptr)
  53. {
  54. return 0;
  55. }
  56. Mat src(Size(Width, Height), CV_16U, input);
  57. memcpy(output, src(Rect(x, y, RectWidth, RectHeight)).clone().data, RectWidth * RectHeight * sizeof(unsigned short));
  58. return 1;
  59. }
  60. int applyInvertMask(unsigned short* input, unsigned char* pmask, int Width, int Height, unsigned short* output,int fillvalue = 4095)
  61. {
  62. if (input == nullptr)
  63. {
  64. return 0;
  65. }
  66. if (pmask == nullptr)
  67. {
  68. return 0;
  69. }
  70. #pragma omp parallel for
  71. for (int i = 0; i < Width * Height; i++)
  72. {
  73. if (!pmask[i])
  74. {
  75. output[i] = fillvalue;
  76. }
  77. else
  78. {
  79. output[i] = input[i];
  80. }
  81. }
  82. return 1;
  83. }