Image 확장
Pixels
pixel과 set_pixel로 이미지의 개별 픽셀을 읽고 바꿉니다.
이미지는 픽셀의 격자입니다
set_pixel(x, y, color)로 한 픽셀의 색을 바꾸고 pixel(x, y)로 읽을 수 있습니다. 좌표는 Window와 마찬가지로 왼쪽 위가 (0, 0)입니다.
먼저 실행해 보세요
예제 · example1.cpp
#include <small/image.h>
void small_main()
{
Image image(256, 256, Black);
for (int y = 0; y < image.height(); y++)
for (int x = 0; x < image.width(); x++)
image.set_pixel(x, y, rgb(x, y, 180));
Window window;
window.open(520, 320);
while (window.is_open())
{
window.clear(Black);
draw_image(window, image, 32, 32);
window.show();
}
}
직접 픽셀을 만들면 알고리즘이 눈에 보입니다
두 겹의 loop로 모든 픽셀을 방문하면 gradient, pattern, 간단한 image processing을 직접 만들 수 있습니다. 범위를 벗어난 pixel 좌표는 오류로 처리됩니다.
한 단계 더
예제 · example2.cpp
#include <small/image.h>
void small_main()
{
Image image(200, 200, Black);
for (int y = 0; y < image.height(); y++)
for (int x = 0; x < image.width(); x++)
if ((x / 20 + y / 20) % 2 == 0)
image.set_pixel(x, y, White);
save_image(image, "checker.png");
print("Saved checker.png");
}
Pixel 작업과 drawing은 분리되어 있습니다
Image 안의 데이터를 바꾸는 것은 member function이고, 그 결과를 Window에 보여주는 것은 draw_image입니다.
Exercise — 대각선
100×100 Black 이미지에 (0,0)부터 (99,99)까지 Yellow 대각선을 그리세요.
연습 문제 코드 · exercise1_starter.cpp
#include <small/image.h>
void small_main()
{
Image image(100, 100, Black);
// Draw a yellow diagonal with set_pixel.
save_image(image, "diagonal.png");
}
Hint
loop의 i를 x와 y에 모두 사용하세요.
풀이 보기
#include <small/image.h>
void small_main()
{
Image image(100, 100, Black);
for (int i = 0; i < 100; i++)
image.set_pixel(i, i, Yellow);
save_image(image, "diagonal.png");
}
Exercise — 픽셀 읽기
Red 이미지의 (10,10) 픽셀을 읽어 Red 성분을 출력하세요.
연습 문제 코드 · exercise2_starter.cpp
#include <small/image.h>
void small_main()
{
Image image(30, 30, Red);
// Read and print the red component.
}
Hint
Color color = image.pixel(10, 10); 다음 color.red()를 사용하세요.
풀이 보기
#include <small/image.h>
void small_main()
{
Image image(30, 30, Red);
Color color = image.pixel(10, 10);
print(color.red());
}