user1804208
user1804208

Reputation: 165

Matlab conversion of pixel values to double precision

I'm new to Matlab so this should be an easy question. I have an image with a few specific pixels that I need to get the red RGB components from, sum them, and store the result into a variable. By default, these values are of type uint8, so the sum can't exceed 255. I've tried using every combination of double() to convert the R value to a double, but nothing seems to be working. Here's exactly what's happening, copied from the terminal: (All pixels have R values above 200)

img = imread('img.png');
r = img(64,64,1)
r =
    224
r = r + double(img(64,65,1))
r =
    255
r = r + double(img(64,66,1))
r =
    255

What am I doing wrong? Am I not able to convert these values to double?

Upvotes: 0

Views: 615

Answers (2)

CKT
CKT

Reputation: 781

What's happening in the line r = r + double(img(64,65,1)) is that the img(64,65,1) value is being converted to double, but then immediately being converted back into class(r) because r is an integer class and has precedence in operations. Observe that class(int64(10)+10) gives back int64. The key here is, as beaker commented, to convert r itself to double first.

You may not have to worry about using double() to do the conversion; doubles can represent integers up to 2^53-1, which is way higher than 255. So if you're just doing simple pixel-summing operations or things like that, you're not going to lose any precision in the calculations. Of course, if you need to put it back into an image, then anything about 255 will saturate. So, it might make more sense depending on what you're doing to rescale things to be between 0 and 1; in that case, as Mingjing suggested, it's best to use im2double.

Upvotes: 0

Mingjing Zhang
Mingjing Zhang

Reputation: 943

For image processing, most of the times it is a good idea to use the im2double function to convert the image read into a double array between 0-1 as such:

img = im2double(imread('img.png'));

Then you don't need to worry about data type any more in the same program.

The data type conversion with double() alone almost never do what you intended to images, since uint8 and double images differ in both data type and data range.

Upvotes: 1

Related Questions