Tahlil
Tahlil

Reputation: 2731

How to convert type of cv:Mat

I tried the following way. Using convertTo function from uchar to CV_32SC1

imgCanny.convertTo(imgCanny32, CV_32SC1);

Which just gives me a blank imageCanny32.

The following way yields the same result.

imgCanny32 = Matrix(imgCanny.size(), CV_32SC1);

for (int i = 0;i < imgCanny.size().height;i++)
            for (int j = 0;j < imgCanny.size().width;j++)
                imgCanny32.at<int>(i,j) = imgCanny.at<uchar>(i,j);

I can't think of any other way.

Upvotes: 1

Views: 1788

Answers (1)

Dan Mašek
Dan Mašek

Reputation: 19041

As you describe it, you begin with an 8-bit one channel image. This means that each pixel is represented by an unsigned byte and as such can have a value between 0 and 255 inclusive.

Next, you perform a cv::Mat::convertTo, using the default values for alpha and beta. This means that in the new Mat, each pixel is represented by a signed 32-bit integer, but the values will remain in the 0-255 inclusive range.

Finally, you pass this Mat to the cv::imshow function. Notice the documentation:

If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].

Since the maximum pixel value the input image contains is 255, and the pixels are divided by 256, the image displayed by the function will appear all black.


That said, both ways of conversion you show are correct, although I'd prefer convertTo, since it will be optimized. If you want to display the CV_32SC1 images, perhaps you should apply an appropriate scaling factor (alpha = 256) for the conversion.

Upvotes: 1

Related Questions