Use the view raw feature (below) if you want to copy the code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
load_libraries :mesh, :control_panel | |
import 'megamu.mesh.Voronoi' | |
attr_reader :voronoi, :img, :pixels, :ready, :upper, :show, :points, :xr, :yr, :lower, :lowskip, :highskip | |
def setup | |
size 500, 500 | |
frame_rate 10 | |
file = select_input "Choose Image File" | |
@img = load_image file | |
(img.height/height <= img.width/width)? @img.resize(0, height) : @img.resize(width, 0) | |
@xr = img.width | |
@yr = img.height | |
@img.load_pixels | |
@img.update_pixels | |
@ready = false | |
@show = false | |
setup_control | |
@points = Array.new | |
puts "done setup" | |
end | |
def setup_control | |
control_panel do |c| | |
c.title = "Control Panel" | |
c.slider :upper, 0..255, 200 | |
c.slider :lower, 0..255, 150 | |
c.slider :lowskip, 1..20, 1 | |
c.slider :highskip, 1..20, 7 | |
# c.button :choose_image | |
c.button :show_voronoi | |
c.button :view_image | |
c.button :save_voronoi | |
end | |
end | |
def show_voronoi | |
no_loop | |
@ready = false | |
@points.clear | |
get_all_points if img | |
@voronoi = Voronoi.new(@points.to_java(Java::float[])) | |
@ready = true | |
loop | |
end | |
def calculate_voronoi | |
regions = voronoi.get_regions | |
stroke(128) | |
fill(0) | |
regions.each do |region| | |
region_coordinates = region.get_coords | |
region.draw(self) | |
end | |
edges = voronoi.get_edges | |
edges.each do |edge| | |
start_x = edge[0] | |
start_y = edge[1] | |
end_x = edge[2] | |
end_y = edge[3] | |
line(start_x, start_y, end_x, end_y) | |
end | |
fill 128 | |
no_stroke | |
end | |
def draw | |
background(0) | |
stroke(128) | |
if (ready) | |
calculate_voronoi | |
end | |
if (show && img) | |
tint(255, 100) | |
image(img, 0, 0) | |
end | |
end | |
# def choose_image | |
# file = select_input("Choose Image File") | |
# @img = load_image(file) | |
# end | |
def mouse_pressed | |
no_loop | |
b = brightness(img.pixels[(mouse_y-1) * xr + mouse_x-1]) if img | |
puts "Brightness = #{b}" | |
loop | |
end | |
def save_voronoi | |
no_loop | |
save_frame | |
puts "finished!" | |
loop | |
end | |
def view_image | |
cursor CROSS | |
@show = !show | |
end | |
def get_all_points | |
x_array = [] | |
y_array = [] | |
x = 0 | |
y = 0 | |
while(x < (xr - highskip)) | |
x_array << x | |
x += (rand * highskip + lowskip).round | |
end | |
while(y < (yr - highskip)) | |
y_array << y | |
y += (rand * highskip + lowskip).round | |
end | |
x_array.each do |pos_x| | |
y_array.each do |pos_y| | |
b = brightness(img.pixels[(pos_y)*xr+pos_x]) | |
if (b <= upper && b >= lower) | |
@points << [pos_x, pos_y] | |
end | |
end | |
end | |
puts "total #{points.size}" | |
end |
No comments:
Post a Comment