Editing images using MATLAB
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
Hi, I found an interesting exercise to do photo editing using matlab but I don't know how to write the convenient script. Here are the steps:
a- Find or take a picture of yourself with a plain background such as a green screen, using the JPEG image format. It would be a good idea not to wear the color of the background.
b- Find a JPEG image of the place you want to go and decide on the rectangle in that scene where your image should appear. Save the width and height of the rectangle and the row and column of its top left corner.
c- Re-size your image to be the width and height of the rectangle.
d- Use the color masking technique to copy your image without the green screen into the selected rectangle of your dream scene.
Thanks a lot!
채택된 답변
Image Analyst
2012년 4월 14일
But isn't the fun of it doing it yourself? Well, I have a demo that does most of it for you. You just have to draw the box, resize to the box and figure out how to shift the mask. But this is a good place to start:
[ Edit] Now it does all that for you.
clc; % Clear the command window.
clearvars;
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
format compact;
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB color demo image.
folder = 'C:\Users\Light\Documents\Temporary';
baseFileName = 'awrdd5.jpg';
fullFileName = fullfile(folder, baseFileName);
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
% Read image from disk.
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original color image.
subplot(2, 3, 1);
imshow(rgbImage, []);
axis on;
title('Original Color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Read in second image.
baseFileName = 'man.jpg';
fullFileName = fullfile(folder, baseFileName);
rgbImage2 = imread(fullFileName);
% Display the second color image.
subplot(2, 3, 2);
imshow(rgbImage2, []);
axis on;
title('Second Color Image', 'FontSize', fontSize);
% Ask user for location using imrect() or rbbox().
subplot(2, 3, 2); % Switch back to first image.
promptMessage = sprintf('Draw a box over the original (first) image');
button = questdlg(promptMessage, 'Draw box', 'OK', 'Cancel', 'OK');
if strcmp(button, 'Cancel')
return;
end
k = waitforbuttonpress;
point1 = get(gca,'CurrentPoint'); % button down detected
finalRect = rbbox; % return figure units
point2 = get(gca,'CurrentPoint'); % button up detected
point1 = point1(1,1:2); % extract x and y
point2 = point2(1,1:2);
p1 = min(point1,point2); % calculate locations
offset = abs(point1-point2); % and dimensions
xCoords = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)];
yCoords = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)];
x1 = round(xCoords(1));
x2 = round(xCoords(2));
y1 = round(yCoords(5));
y2 = round(yCoords(3));
% Plot the mask as an outline over the image.
hold on;
plot(xCoords, yCoords, 'linewidth', 2);
% Resize rgbImage2
% Call to imresize()
% Here, I'll just resize to size of the box.
newRows = abs(y2-y1)+1;
newColumns = abs(x2-x1)+1
rgbImage2 = imresize(rgbImage2, [newRows newColumns]);
[rows2 columns2 numberOfColorBands2] = size(rgbImage);
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Same, but this time for the second image.
redChannel2 = rgbImage2(:, :, 1);
greenChannel2 = rgbImage2(:, :, 2);
blueChannel2 = rgbImage2(:, :, 3);
% Get the mask - it's where the red channel is brighter than 55.
mask = greenChannel2 < 171; % A logical image.
% Fill in holes
mask = imfill(mask, 'holes');
% Display the mask image.
subplot(2, 3, 3);
imshow(mask, []);
title('Binary Mask', 'FontSize', fontSize);
axis on;
% Multiply the mask by the images to get just the football
% and not the background.
maskedRed = redChannel2 .* uint8(mask);
maskedGreen = greenChannel2 .* uint8(mask);
maskedBlue = blueChannel2 .* uint8(mask);
% Stack all the color channels back into the 3D true color image.
maskedRgbImage = cat(3, maskedRed, maskedGreen, maskedBlue);
% Display the masked second color image.
subplot(2, 3, 4);
imshow(maskedRgbImage, []);
axis on;
title('Masked Color Image', 'FontSize', fontSize);
% Make a large mask for the original picture.
bigMask = false(size(redChannel));
% Now insert the small mask into it.
bigMask(y1:y2, x1:x2) = mask;
% Insert rgbImage2 into rgbImage.
% Assign only image pixels, not background pixels.
redChannel(bigMask) = redChannel2(mask);
greenChannel(bigMask) = greenChannel2(mask);
blueChannel(bigMask) = blueChannel2(mask);
rgbImage3 = cat(3, redChannel, greenChannel, blueChannel);
% Display the second color image.
subplot(2, 3, 5);
imshow(rgbImage3, []);
axis on;
title('Output Color Image', 'FontSize', fontSize);
msgbox('Done with demo. Thanks ImageAnalyst!');
댓글 수: 12
Thank you very much!
Do someone have a simpler answer? because i'm just begining in MATLAB and the previous answer is too complicated for me :/
Image Analyst
2012년 4월 14일
이동: DGM
2023년 2월 12일
No it's not. It's well commented and you're a smart engineer so if you take it a line at a time it will be no problem for you. Did you actually run it or just look at the entirety of it and say that's too much code for me to understand? Break it down into small chunks (the one or two lines of code after the comment that explains what it will do) and see if you can follow. If there's a particular line that is not well explained by the comment, ask me. Sure I could make it more compact by leaving out comments and making other assumptions but it would be harder to follow.
Harsha Vardhan Rao Avunoori
2012년 4월 14일
이동: DGM
2023년 2월 12일
@Light...Trust me Mr.Image Analyst is the most experienced professional in this group and he has helped me in fixing my code...Understand the way it is written use the MATLAB Help if you are not clear with the syntax or not sure what would a particular function does in the code and you should be good!!! This group helps quite a lot to students and professionals who share a passion and enthusiasm towards MATLAB...So all the best and give it a try.
Ok thank you for your help I'll do my best.
Hi, I found that the code doesn't really solve the exercice because i have the picture of a person with all the background green, and i have a picture of a scenery and the purpose is to insert just the person without the green background into the scenery but the script seems not to do it. Can i use this code to solve the exercise?
v = imread('person.jpg');
w = imread('scenery.jpg');
thres = 230;
layer = (v(:,:,1) > thres) & (v(:,:,2) > thres) & (v(:,:,3) > thres);
mask(:,:,1) = layer;
mask(:,:,2) = layer;
mask(:,:,3) = layer;
nv = v;
nv(mask) = w(mask);
image(nv);
imwrite(nv, 'finalpic.jpg', 'jpg')
Thank you!
Image Analyst
2012년 4월 16일
이동: DGM
2023년 2월 12일
Well somehow you messed up when you tried to adapt it. In your code, it will fail as soon as it sees that mask line. It's time for you to upload your images somewhere, like tinypic.com, so I can see this challenging image and figure out why my code doesn't work with it, or can't be adapted to work with it.
let's take this guy as an example: http://i42.tinypic.com/xyikl.jpg
and the scenery: http://i43.tinypic.com/awrdd5.jpg
Image Analyst
2012년 4월 16일
이동: DGM
2023년 2월 12일
Looks like you picked the wrong thresholds. I used <171 and you used >230. Look in the Accepted Answer above. I've edited it so that now I've done the whole thing for you, even the box drawing part, resizing the image, masking it, and placing it in the original image. All you have to do is to change the folder, and the image names to what they are on your computer.
Thank you so much! I really appreciate your help.
Tahreen Isha
2018년 6월 8일
편집: Tahreen Isha
2018년 6월 8일
I get the following error while extracting the green and blue channels:
Index exceeds matrix dimensions.
Error in editor (line 101)
rgbImage(:, :, 2)
UPDATE: I was using .tif images. Using .jpg gives no error.
Walter Roberson
2018년 6월 8일
편집: Walter Roberson
2024년 11월 29일
Whatever image you were dealing with at the time was not an RGB image.
The image you were using was probably a color-mapped image for which you needed
[TheImage, ColorMap] = imread(FileName);
if ~isempty(ColorMap); TheImage = ind2rgb(TheImage,Colormap); end
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Blue에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
