sw 3 days ago
commit
042925bf36
1 changed files with 119 additions and 0 deletions
  1. 119 0
      utils.cpp

+ 119 - 0
utils.cpp

@@ -0,0 +1,119 @@
+#include <iostream>
+#include <opencv2/opencv.hpp>
+
+using namespace cv;
+using namespace std;
+
+void show(Mat src, const char wd[], float i = 0.3) {
+
+    int maxs = src.cols > src.rows ? src.cols : src.rows;
+    float ra = 400 / (maxs + DBL_MIN);
+    i = ra;
+    //------չʾͼÏñ²Ù×÷------
+    namedWindow(wd, WINDOW_FREERATIO);
+    if (i > 100)
+    {
+        resizeWindow(wd, i, i);//´°¿Ú³ß´çµ÷½Ú
+    }
+    else
+    {
+        resizeWindow(wd, int(i * src.cols), int(i * src.rows));//´°¿Ú³ß´çµ÷½Ú
+    }
+    Mat src1 = src.clone();
+    src1.convertTo(src1, 5);
+    normalize(src1, src1, 0, 1, NORM_MINMAX);
+
+    imshow(wd, src1);
+
+
+    waitKey(0);
+}
+
+int applyMask(unsigned short* input, unsigned char* pmask, int Width, int Height, unsigned short* output)
+{
+    if (input == nullptr)
+    {
+        return 0;
+    }
+    if (pmask == nullptr)
+    {
+        return 0;
+    }
+
+    Mat src(Size(Width, Height), CV_16U, input);
+    Mat mask(Size(Width, Height), CV_8U, pmask);
+    Mat result;
+    bitwise_and(src, src, result, mask);
+  
+    if (result.empty() || result.rows != Height || result.cols != Width )
+    {
+        return 0;
+    }
+    memcpy(output, result.data, Width * Height * sizeof(unsigned short));
+
+    return 1;
+}
+
+int getMaskRect(unsigned char* pmask, int Width, int Height, int &x,int &y,int &RectWidth,int &RectHeight)
+{
+    if (pmask == nullptr)
+    {
+        return 0;
+    }
+
+    Mat mask(Size(Width, Height), CV_8U, pmask);
+
+    if (!sum(mask)[0])
+    {
+        return 0;
+    }
+
+    cv::Mat nonZeroPoints;
+    cv::findNonZero(mask, nonZeroPoints);
+    cv::Rect rect = cv::boundingRect(nonZeroPoints);
+
+    x = rect.x;
+    y = rect.y;
+    RectWidth = rect.width;
+    RectHeight = rect.height;
+    
+    return 1;
+}
+
+int cropImg(unsigned short *input, unsigned short *output, int Width, int Height, int x, int y, int RectWidth, int RectHeight)
+{
+    if (input == nullptr)
+    {
+        return 0;
+    }
+    if (output == nullptr)
+    {
+        return 0;
+    }
+
+    Mat src(Size(Width, Height), CV_16U, input);
+    memcpy(output, src(Rect(x, y, RectWidth, RectHeight)).clone().data, RectWidth * RectHeight * sizeof(unsigned short));
+
+    return 1;
+}
+
+
+int main()
+{
+    Mat input = imread(R"(Image_FinalImage.tif)",-1);
+    Mat mask = imread(R"(mask.tif)", -1);
+   
+    int x = 0;
+    int y = 0;
+    int width = 0;
+    int height = 0;
+    getMaskRect(mask.ptr<uchar>(), input.cols, input.rows, x, y, width, height);
+    
+    unsigned short* output = new unsigned short[width * height];
+    cropImg(input.ptr<ushort>(), output,input.cols,input.rows,x,y,width,height);
+
+    Mat result(Size(width, height), CV_16U, output);
+    show(result, "result");
+
+	return 0;
+}