LoginSignup
4
3

More than 5 years have passed since last update.

mruby でリアルタイムで映像分類する

Posted at

@akuroda さんが mruby-gdを使って画素にアクセスする方法を教えてくれたので @kjunichi さんの mruby-webcam を使ってリアルタイムに映像分類する様にしてみました。

導入の方法は akuroda さんの記事を読んで下さい。

model = TfLite::Model.from_file 'mobilenet_v1_1.0_224_quant.tflite'
interpreter = TfLite::Interpreter.new(model)
interpreter.allocate_tensors
input = interpreter.input_tensor(0)
output = interpreter.output_tensor(0)
wanted_width = input.dim(1)
wanted_height = input.dim(2)
wanted_channel = input.dim(3)
data = Array.new(wanted_height * wanted_width * wanted_channel, 0)
labels = File.read('labels.txt').lines.map {|x| x.strip} 

cam = Webcam.new(ARGV[0]||0)
cam.set_size(wanted_width, wanted_height)
cam.each(true) {|img|
  decoded = GD::Image.new_from_jpeg_data(img)
  (0...wanted_width).each do |x|
    (0...wanted_height).each do |y|
      pixel = decoded.get_pixel(x, y)
      offset = (y * wanted_width + x) * wanted_channel
      data[offset+0] = decoded.red(pixel)
      data[offset+1] = decoded.green(pixel)
      data[offset+2] = decoded.blue(pixel)
    end
  end
  decoded.destroy
  input.data = data
  interpreter.invoke
  output.data.each_with_index do |v, i|
    puts "#{i} #{v} #{labels[i]}" if v > 50
  end 
  puts "---"
}

cam.each はまだマージされてないので今しばらくお待ちください。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3