class NSFW::Image
Constants
- DIMENSIONS
- PIXEL_NORMAL
Attributes
img[RW]
Public Class Methods
model()
click to toggle source
# File lib/nsfw/image.rb, line 8 def model @_model ||= NSFW::Model.new(lazy: true) end
new(image_path)
click to toggle source
# File lib/nsfw/image.rb, line 18 def initialize(image_path) @img = MiniMagick::Image.open(image_path) end
predictions(image_path)
click to toggle source
# 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)
click to toggle source
# File lib/nsfw/image.rb, line 22 def self.prepare!(image_path) img = new(image_path) img.process! img end
safe?(image_path)
click to toggle source
# File lib/nsfw/image.rb, line 48 def self.safe?(image_path) img = self.prepare!(image_path) model.safe?(img) end
unsafe?(image_path)
click to toggle source
# File lib/nsfw/image.rb, line 53 def self.unsafe?(image_path) !self.safe?(image_path) end
Public Instance Methods
dimensions()
click to toggle source
# File lib/nsfw/image.rb, line 36 def dimensions @img.dimensions end
pixels()
click to toggle source
# File lib/nsfw/image.rb, line 40 def pixels @_pixels ||= @img.get_pixels end
process!()
click to toggle source
# 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
tensor()
click to toggle source
# File lib/nsfw/image.rb, line 44 def tensor @_normalized_pixels ||= normalize_pixels!(pixels) end
Private Instance Methods
crop!()
click to toggle source
Crop to 244x244 after resizing
# File lib/nsfw/image.rb, line 70 def crop! @img.crop("#{DIMENSIONS}") end
normalize_pixels!(pixel_tensor)
click to toggle source
Normalize pixels between 0-1
# File lib/nsfw/image.rb, line 80 def normalize_pixels!(pixel_tensor) if pixel_tensor.is_a?(Integer) return pixel_tensor.to_f/PIXEL_NORMAL.to_f else return pixel_tensor.map{ |a| normalize_pixels!(a) } end # tensor.map do |i| # i.map do |j| # j.map do |k| # k.to_f / 255.0 # end # end # end end
resize!()
click to toggle source
Resize to the dimensions needed by the model (244px x 244px)
# File lib/nsfw/image.rb, line 65 def resize! @img.resize("#{DIMENSIONS}^") end
stash!()
click to toggle source
Save to tmpfile
# File lib/nsfw/image.rb, line 75 def stash! @img.write() end