Sha256: 5bf20d62b24259caf5f635b13ac401b8fc4562d01fc9d2de3a78afcd34c71885

Contents?: true

Size: 1.25 KB

Versions: 21

Compression:

Stored size: 1.25 KB

Contents

require "numo/narray"
require "dnn/ext/rb_stb_image/rb_stb_image"

module DNN
  module ImageIO
    def self.read(file_name)
      raise ImageIO::ReadError.new("#{file_name} is not found.") unless File.exist?(file_name)
      bin, w, h, n = Stb.stbi_load(file_name, 3)
      img = Numo::UInt8.from_binary(bin)
      img.reshape(h, w, 3)
    end

    def self.write(file_name, img, quality: 100)
      if img.shape.length == 2
        img = Numo::UInt8[img, img, img].transpose(1, 2, 0).clone
      elsif img.shape[2] == 1
        img = img.shape(img.shape[0], img.shape[1])
        img = Numo::UInt8[img, img, img].transpose(1, 2, 0).clone
      end
      h, w, ch = img.shape
      bin = img.to_binary
      case file_name
      when /\.png$/
        stride_in_bytes = w * ch
        Stb.stbi_write_png(file_name, w, h, ch, bin, stride_in_bytes)
      when /\.bmp$/
        Stb.stbi_write_bmp(file_name, w, h, ch, bin)
      when /\.jpg$/
        Stb.stbi_write_jpg(file_name, w, h, ch, bin, quality)
      end
    rescue => ex
      raise ImageIO::WriteError.new(ex.message)
    end
  end

  class ImageIO::Error < StandardError; end

  class ImageIO::ReadError < ImageIO::Error; end

  class ImageIO::WriteError < ImageIO::Error; end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
ruby-dnn-0.6.3 lib/dnn/lib/image_io.rb
ruby-dnn-0.6.2 lib/dnn/lib/image_io.rb
ruby-dnn-0.6.1 lib/dnn/lib/image_io.rb
ruby-dnn-0.6.0 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.12 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.11 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.10 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.9 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.8 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.7 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.6 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.5 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.4 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.3 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.2 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.1 lib/dnn/lib/image_io.rb
ruby-dnn-0.5.0 lib/dnn/lib/image_io.rb
ruby-dnn-0.4.4 lib/dnn/lib/image_io.rb
ruby-dnn-0.4.3 lib/dnn/lib/image_io.rb
ruby-dnn-0.4.2 lib/dnn/lib/image_io.rb