How can I pass an image to a figure ?

조회 수: 4 (최근 30일)
Doug Leaffer
Doug Leaffer 2025년 5월 8일
댓글: Adam Danz 2025년 5월 8일
Hello. How can I pass an image to a figure in a MATLAB script?
% Generate a wood grain pattern (example)
grain = rand(300, 400);
grain_thresholded = grain > 0.5; % Creates a binary pattern
% Apply color values to simulate wood grain
image(:,:,1) = grain_thresholded * 0.8 + (1 - grain_thresholded) * 0.4; % Red
image(:,:,2) = grain_thresholded * 0.6 + (1 - grain_thresholded) * 0.2; % Green
image(:,:,3) = grain_thresholded * 0.3 + (1 - grain_thresholded) * 0.1; % Blue
% Display the image
figure;
imshow(image);
The existing figure code is below. I want to replace the brown/tan RGB figure color with the above image color and pattern. Thanks for any help !
% Plot beam cross section
% A = base*h; % beam area, in^2
figure()
pgon = polyshape([0 0 23.5 23.5],[12 0 0 12]);
H = plot(pgon,'FaceColor',[0.666, 0.392, 0.196],'FaceAlpha',0.5); % use 0.666, 0.392, 0.196
% RGB: (202 164 114) = 0.79 0.643 0.447 wood color
H.LineStyle = '--';
H.EdgeColor = 'black';
hold on
axis equal
grid on
x6 =[0 23.5];
y6 =[6 6];
line(x6,y6,'Color','red','LineStyle','-.') % adds a line at 'c = 6'
title('Cross Section of Designed Beam')
xlabel('base (in)'); ylabel('height (depth) (in)')

채택된 답변

Adam Danz
Adam Danz 2025년 5월 8일
편집: Adam Danz 2025년 5월 8일
Use image and specify the x and y limits instead of using polyshape.
% Generate a wood grain pattern (example)
grain = rand(300, 400);
grain_thresholded = grain > 0.5; % Creates a binary pattern
% Apply color values to simulate wood grain
I(:,:,1) = grain_thresholded * 0.8 + (1 - grain_thresholded) * 0.4; % Red
I(:,:,2) = grain_thresholded * 0.6 + (1 - grain_thresholded) * 0.2; % Green
I(:,:,3) = grain_thresholded * 0.3 + (1 - grain_thresholded) * 0.1; % Blue
figure()
image([0 23.5], [0 12], I, AlphaData=0.5)
hold on
axis equal padded
grid on
x6 =[0 23.5];
y6 =[6 6];
line(x6,y6,'Color','red','LineStyle','-.') % adds a line at 'c = 6'
title('Cross Section of Designed Beam')
xlabel('base (in)'); ylabel('height (depth) (in)')
  댓글 수: 2
Doug Leaffer
Doug Leaffer 2025년 5월 8일
Thanks Adam. Your code worked when I passed it to a function wood(b, h, c) -- which are my variables, and called the wood function from a .mlx live script. For some reason the code did not execute without errors if I simply copied it into the live script with no function call.
Adam Danz
Adam Danz 2025년 5월 8일
I just copied it into a live script in R2024b and it ran without any issues. If you continue to have this issue, I recommend contacting tech support. Glad it worked for you otherwise!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Elementary Polygons에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by