Module: DNN::Image

Defined in:
lib/dnn/image.rb

Defined Under Namespace

Classes: ImageError, ImageReadError, ImageShapeError, ImageWriteError

Constant Summary collapse

RGB =
3
RGBA =
4

Class Method Summary collapse

Class Method Details

.gray_scale(img) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/dnn/image.rb', line 59

def self.gray_scale(img)
  img_check(img)
  if img.shape[2] == RGB
    x = Numo::SFloat.cast(img)
    x = x.mean(axis: 2, keepdims: true)
  elsif img.shape[2] == RGBA
    x = Numo::SFloat.cast(img[true, true, 0..2])
    x = x.mean(axis: 2, keepdims: true).concatenate(img[true, true, 3..3], axis: 2)
  end
  Numo::UInt8.cast(x)
end

.read(file_name, channel_type = RGB) ⇒ Object

Raises:



17
18
19
20
21
22
23
# File 'lib/dnn/image.rb', line 17

def self.read(file_name, channel_type = RGB)
  raise ImageReadError.new("#{file_name} is not found.") unless File.exist?(file_name)
  bin, w, h, n = Stb.stbi_load(file_name, channel_type)
  raise ImageReadError.new("#{file_name} load failed.") if bin == ""
  img = Numo::UInt8.from_binary(bin)
  img.reshape(h, w, channel_type)
end

.resize(img, out_height, out_width) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/dnn/image.rb', line 46

def self.resize(img, out_height, out_width)
  img_check(img)
  in_height, in_width, ch = *img.shape
  out_bin, res = Stb.stbir_resize_uint8(img.to_binary, in_width, in_height, 0, out_width, out_height, 0, ch)
  img2 = Numo::UInt8.from_binary(out_bin).reshape(out_height, out_width, ch)
  img2
end

.trim(img, y, x, height, width) ⇒ Object



54
55
56
57
# File 'lib/dnn/image.rb', line 54

def self.trim(img, y, x, height, width)
  img_check(img)
  img[y...(y + height), x...(x + width), true].clone
end

.write(file_name, img, quality: 100) ⇒ Object

Raises:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/dnn/image.rb', line 25

def self.write(file_name, img, quality: 100)
  img_check(img)
  match_data = file_name.match(%r`(.*)/.+$`)
  if match_data
    dir_name = match_data[1]
    Dir.mkdir(dir_name) unless Dir.exist?(dir_name)
  end
  h, w, ch = img.shape
  bin = img.to_binary
  case file_name
  when /\.png$/i
    stride_in_bytes = w * ch
    res = Stb.stbi_write_png(file_name, w, h, ch, bin, stride_in_bytes)
  when /\.bmp$/i
    res = Stb.stbi_write_bmp(file_name, w, h, ch, bin)
  when /\.jpg$/i, /\.jpeg/i
    res = Stb.stbi_write_jpg(file_name, w, h, ch, bin, quality)
  end
  raise ImageWriteError.new("Image write failed.") if res == 0
end