Converting an image to grayscale problem

1 次查看(过去 30 天)
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.

回答(1 个)

Image Analyst
Image Analyst 2014-11-10
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 个评论
Ray
Ray 2014-11-10
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.
Image Analyst
Image Analyst 2014-11-10
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);

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Modify Image Colors 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by