utils.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. }