画像の一部を切り取るサンプルです。
マウスカーソルで切り取る画像の位置を指定しています。
clip.rb
# 矩形サイズ
SIZE = 30
def setup
size 300, 300
@image = load_image('./image/study_daigakusei_man.png')
@image.load_pixels
# 切り取ったイメージの格納先
@clipimage = create_image(SIZE, SIZE, ARGB)
end
def draw
background 255
image(@image, 0, 0)
stroke 255, 0, 0
no_fill
rect_mode CENTER
rect mouse_x, mouse_y, SIZE, SIZE
# 矩形内のピクセルを @clipimage にコピー
for i in 0..SIZE-1
for j in 0..SIZE-1
x = mouse_x - SIZE/2 + j
y = mouse_y - SIZE/2 + i
p = y * @image.width + x
if x <= @image.width && 0 <= p && p < @image.width * @image.height
@clipimage.pixels[i * SIZE + j] = @image.pixels[p]
else
@clipimage.pixels[i * SIZE + j] = color(255, 255, 255)
end
end
end
@clipimage.update_pixels
# 切り取ったイメージを描画
image(@clipimage, 200, 200)
stroke 0
rect 200+SIZE/2, 200+SIZE/2, SIZE, SIZE
end
コマンドラインから次のように実行します。
$ rp5 run --nojruby clip.rb
参考
- rp_samples/samples/processing_app/topics/image_processing/edge_detection.rb
- Ruby-Processing 付属のサンプル