Converting an image to grayscale problem

I'm supposed to convert a 3'd matrix which represents an image to a 2-d grayscale matrix, but am running into the following error with my code:
function [gray] = convertImageToGrayscale(orig)
% Takes in a 3-d Matrix and converts it to 2-d
gray = .299*orig(:,:,1) + .587*orig(:,:,2) + .114*orig(:,:,3);
gray = uint8(gray);
end
Error: Integers can only be combined with integers of the same class, or scalar doubles.
How do I fix this? Any help would be appreciated.

Answers (1)

gray() is a built in function so don't use that for a variable.
There should not be any problem with that code. Here's proof:
close all;
% Create a uint8 RGB image.
orig = uint8(randi(255, 100,100,3));
% Display it.
subplot(1,2,1);
imshow(uint8(orig));
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Takes in a 3-d Matrix and converts it to 2-d
grayImage = .299*orig(:,:,1) + .587*orig(:,:,2) + .114*orig(:,:,3);
grayImage = uint8(grayImage);
subplot(1,2, 2);
imshow(grayImage);
You must have gotten that error message from some other code. Please post that code.

4 Comments

I am getting that error from that code. Should I declare grayImage as a double?
I don't believe that if you copy and paste my code that you could get that error message. I didn't when I ran it and you should not either. Multiplying an integer of any class by a double is allowed. And .299, .587, and .114 are not integers. What is not allowed is to multiply a uint8 by a uint16 or some other class of integer. Copy and paste your entire error message here - the whole thing - all the red text with line numbers, lines of code, etc.
This is for a project in class. Basically, I am only allowed to run an autograder on the code and the autograder gives me this error after testing it against an image:
Beginning convertImageToGrayscale.m easy test 1... Checking student output against reference... test aborted. Error caught and test failed. Error: Integers can only be combined with integers of the same class, or scalar doubles.
Well the autograder is wrong . You ARE combining an integer with a scalar double, which it explicitly says IS allowed. So try casting the images to double to get around the stupidity of the autograder.
orig = double(orig);
gray = .299*orig(:,:,1) + .587*orig(:,:,2) + .114*orig(:,:,3);

Sign in to comment.

Asked:

Ray
on 10 Nov 2014

Commented:

on 10 Nov 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!