Class: NSFW::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/nsfw/image.rb

Constant Summary collapse

DIMENSIONS =
"224x224"
PIXEL_NORMAL =
255

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(image_path) ⇒ Image

Returns a new instance of Image.



18
19
20
# File 'lib/nsfw/image.rb', line 18

def initialize(image_path)
  @img = MiniMagick::Image.open(image_path)
end

Instance Attribute Details

#imgObject

Returns the value of attribute img.



16
17
18
# File 'lib/nsfw/image.rb', line 16

def img
  @img
end

Class Method Details

.modelObject



8
9
10
# File 'lib/nsfw/image.rb', line 8

def model
  @_model ||= NSFW::Model.new(lazy: true)
end

.predictions(image_path) ⇒ Object



57
58
59
60
# File 'lib/nsfw/image.rb', line 57

def self.predictions(image_path)
  img = self.prepare!(image_path)
  model.predict(img.tensor)
end

.prepare!(image_path) ⇒ Object



22
23
24
25
26
# File 'lib/nsfw/image.rb', line 22

def self.prepare!(image_path)
  img = new(image_path)
  img.process!
  img
end

.safe?(image_path) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
51
# File 'lib/nsfw/image.rb', line 48

def self.safe?(image_path)
  img = self.prepare!(image_path)
  model.safe?(img)
end

.unsafe?(image_path) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/nsfw/image.rb', line 53

def self.unsafe?(image_path)
  !self.safe?(image_path)
end

Instance Method Details

#dimensionsObject



36
37
38
# File 'lib/nsfw/image.rb', line 36

def dimensions
  @img.dimensions
end

#pixelsObject



40
41
42
# File 'lib/nsfw/image.rb', line 40

def pixels
  @_pixels ||= @img.get_pixels
end

#process!Object



28
29
30
31
32
33
34
# File 'lib/nsfw/image.rb', line 28

def process!
  @img.colorspace("RGB")
    .resize("#{DIMENSIONS}^")
    .crop("#{DIMENSIONS}+0+0","-gravity", "center")
    .write(Tempfile.new.path)
  @img
end

#tensorObject



44
45
46
# File 'lib/nsfw/image.rb', line 44

def tensor
  @_normalized_pixels ||= normalize_pixels!(pixels)
end