Skip to content

Instantly share code, notes, and snippets.

@uozias
Created January 19, 2016 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uozias/f4dcc72681a7fb1264b9 to your computer and use it in GitHub Desktop.
Save uozias/f4dcc72681a7fb1264b9 to your computer and use it in GitHub Desktop.
require 'opencv'
require 'serialport'
window = OpenCV::GUI::Window.new "Camera"
capture = OpenCV::CvCapture.open
window2 = OpenCV::GUI::Window.new "LED"
width = 2880/10
height = 1800/ 10
# シリアルポート利用準備
@serial_port = "/dev/cu.usbmodem1421" #シリアルのポートを指定。OSによって違うので確認のこと。
@serial_bps = 9600
sp = SerialPort.new(@serial_port,@serial_bps)
#
# 映像を左右の領域に分けて、各領域の色を全部足していく
#
def get_new_pixel(pixel, col, width, new_pixels)
# right
target = new_pixels[:right]
if col > (width/2)
# left
target = new_pixels[:left]
end
(0..2).each do |num|
target[num] += pixel[num]
end
new_pixels
end
loop do
#
# 左右の画像の色ごとの合算値を入れる変数
#
new_pixels = {
right: [
0,
0,
0
],
left: [
0,
0,
0
]
}
#
# 元画像の表示と各ピクセルの保存
#
image = capture.query
image = image.resize OpenCV::CvSize.new width, height # 元画像
image2 = OpenCV::IplImage.new width, height # LED模擬
row_num = image.rows
col_num = image.cols
(0..(row_num-1)).each do |row|
(0..(col_num-1)).each do |col|
pixel = image.at(row, col)
new_pixel = get_new_pixel(pixel, col, width, new_pixels)
end
end
window.show image
#
# 劣化後の画面を表示
#
scalars = {
left: nil,
right: nil
}
colors = {
left: nil,
right: nil,
}
[:left, :right].each do |left_or_right|
new_pixel = [0, 0, 0]
target = new_pixels[left_or_right]
if target[0] > target[1] and target[0] > target[2]
new_pixel = [255, 0, 0]
colors[left_or_right] = :blue
end
if target[1] > target[0] and target[1] > target[2]
new_pixel = [0, 255, 0]
colors[left_or_right] = :green
end
if target[2] > target[0] and target[2] > target[1]
new_pixel = [0, 0, 255]
colors[left_or_right] = :red
end
scalars[left_or_right] = OpenCV::CvScalar.new(new_pixel[0], new_pixel[1], new_pixel[2])
end
(0..(row_num-1)).each do |row|
(0..(col_num-1)).each do |col|
target = :right
if col > (width/2)
# left
target = :left
end
num = (row )*width+col
image2[num] = scalars[target]
end
end
window2.show image2
#
# LEDを光らせる
#
led_code = {
right:{
red:1,
green:2,
blue:3,
},
left: {
red:4,
green:5,
blue:6,
}
}
number = 999
[:left, :right].each do |left_or_right|
number = led_code[left_or_right][colors[left_or_right]]
sp.write(number) #serialへの書き込み 数字+数字以外
sp.write("¥")
end
break if OpenCV::GUI::wait_key(100)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment