Changing the type (interpretation) of cv :: Mat image

For some reason, I have a .tiff image that is incorrectly entered by OpenCV cv::imread as CV_16U instead of CV_16S . I know this is wrong because my data was explained to me (the image should contain dummy values ​​of -9999 and a positive maximum value), and I get the correct values ​​when entering into Matlab .

I can still handle this for example. the .at<type> function itself, since I know the real type, so I can use .at<short> . However, cv::Mat::type() is wrong, which is undesirable if I use other functions for further processing that can rely on this parameter (where processing may depend on cv::Mat::type() ) .

How to change cv::Mat::type() without image conversion? That is, I do not want the values ​​to be recalculated from the unsigned short representation to short , but just the way they are read for change.

How to change cv::Mat::type() associated with an image. (but don't just convert the image to another type).

Here is a sample code and its output to illustrate the problem:

 cv::Mat test = cv::imread(argv[1], CV_LOAD_IMAGE_ANYDEPTH); if (test.type() == CV_16U){ // true std::cerr << (short)(*std::min_element(test.begin<short>(), test.end<short>())) << std::endl; std::cerr << (short)(*std::max_element(test.begin<short>(), test.end<short>())) << std::endl; // output is OK, "-9999" and "1645" std::cerr << (unsigned short) (*std::min_element(test.begin<unsigned short>(), test.end<unsigned short>())) << std::endl; std::cerr << (unsigned short) (*std::max_element(test.begin<unsigned short>(), test.end<unsigned short>())) << std::endl; // output is not OK: "1" and "55537" cv::Mat test2; test.convertTo(test2, CV_16S); // also tried: // test.assignTo(test2, CV_16S); std::cerr << (short)(*std::min_element(test2.begin<short>(), test2.end<short>())) << std::endl; std::cerr << (short)(*std::max_element(test2.begin<short>(), test2.end<short>())) << std::endl; // output is not OK: "1" and "32767" test.type = CV_16U; // what I would like to do } 
0
c ++ image-processing opencv
source share
1 answer

OpenCV leaves its data members public by default (although you generally don't want to contact them). Go ahead and try this; if it works Great! if not good ...

Warning: untested and hacked solution

 test.flags = (test.flags & ~CV_MAT_TYPE_MASK) | CV_16S; 
+2
source share

All Articles