Bran Ton wrote some non-robust code when he did this:
[img_h, img_w] = size(img);
Never do that with an image. If img happens to be a color image, img_w will give you the number of columns times the number of color channels (3) instead of the number of columns like you were expecting. He should have done this:
That line is wrong. You are reading in in RGB image, so it is 3 dimensional. When you use fewer outputs for a size() call than the array has dimensions, then the final output (in this case img_w) will be assigned the product of all remaining dimensions. The array is 192 x 256 x 3, so img_h will be assigned 192, and img_w will be assigned (256 * 3) = 768.
Your code then proceeds to process the input image as if it were an array with size(img,3) = 3 times as many columns as it really has, so you get an array that has 768 columns on output. You then try to do computation between that array of width 768 and the original image of width 256.
I am sure that when you displayed the image that it looked like a grayscale image, but it is an RGB image that happens to only use shades of gray.
Best Answer