카테고리
Course Basiccourse-basic
코드와 해설을 함께 읽는 학습 문서
Code Detail
이미지를 로드하여 변조하고 그리기
course/basic/demo-13.m
코드를 복사해 Octave에서 바로 실행할 수 있습니다.
76 lines
# filename: demo-13.m
# writer: won sunggyu
# date: 2025-04-22
# language: octave
# description: 이미지를 로드하여 변조하고 그리기
#------------------------------------------------------------------------------
# 초기화
#------------------------------------------------------------------------------
run("startup.m");
printf(fmt("{mfilename}\n", "#FF5733"));
#------------------------------------------------------------------------------
# 데이터 준비
#------------------------------------------------------------------------------
filename = "fruit.jpg";
img = imread(filename);
[height, width, channel] = size(img); % 340 x 511 x 3
R = img(:, :, 1); % 340 x 511
G = img(:, :, 2); % 340 x 511
B = img(:, :, 3); % 340 x 511
#------------------------------------------------------------------------------
# 데이터 연산
#------------------------------------------------------------------------------
# RGB to Grayscale 변환
gray_img = rgb2gray(img);
# 사과와 바나나의 색상 마스크 생성
mask_1 = R > 100 & R > G + 80 & R > B + 80; % 340 x 511
mask_2 = G > 100 & G < R - 20 & G > B + 20; % 340 x 511
apple_only = img;
apple_only(repmat(~mask_1, [1,1,3])) = 255;
banana_only = img;
banana_only(repmat(~mask_2, [1,1,3])) = 255;
% 외곽선 추출 (입력 흑백, 출력은 점으로 표시됨)
% "sobel", "canny", "prewitt"
edge_sobel_mask = edge(uint8(mask_1) * 255, "sobel");
edge_sobel_img = uint8(~edge_sobel_mask) * 255;
edge_canny_mask = edge(uint8(mask_1) * 255, "canny");
edge_canny_img = uint8(~edge_canny_mask) * 255;
#------------------------------------------------------------------------------
# 그래프 그리기
#------------------------------------------------------------------------------
figured("Size", [1440, 960], "Move", [-1280, 0], "Name", mfilename);
ax1 = subplots(2, 3);
imshow(img, "Parent", ax1(1, 1));
imshow(repmat(gray_img, [1, 1, 3]), "Parent", ax1(1, 2));
imshow(apple_only, "Parent", ax1(2, 1));
imshow(banana_only, "Parent", ax1(2, 2));
imshow(repmat(edge_sobel_img, [1, 1, 3]), "Parent", ax1(1, 3));
imshow(repmat(edge_canny_img, [1, 1, 3]), "Parent", ax1(2, 3));
set(ax1(1, 1), "Title", "Original Image");
set(ax1(1, 2), "Title", "Grayscale Image");
set(ax1(2, 1), "Title", "Apple Only Image");
set(ax1(2, 2), "Title", "Banana Only Image");
set(ax1(1, 3), "Title", "Sobel Edge Image");
set(ax1(2, 3), "Title", "Canny Edge Image");
set_axes_layout(ax1, [1, 1], [1, 1, 1]);