2014-06-30 46 views
0

如何在Ruby-On-Rails應用程序中使用諸如Textcleaner的腳本?目前,我正在使用自定義回形針處理器,其中使用了與腳本相似的參數。這裏是我的ActiveRecord的has_attached_file線:在Ruby-On-Rails中用於OCR的乾淨圖像附件

has_attached_file :file, :style=> { :processors => [:text_cleaner] } } 

這是回形針處理器:

module Paperclip 
    # Handles grayscale conversion of images that are uploaded. 
    class TextCleaner< Processor 

    def initialize file, options = {}, attachment = nil 
     super 
     @format = File.extname(@file.path) 
     @basename = File.basename(@file.path, @format) 
    end 

    def make 
     src = @file 
     dst = Tempfile.new([@basename, @format]) 
     dst.binmode 

     begin 
     parameters = [] 
     parameters << ":source" 
     parameters << "-auto-orient" 
     parameters << "-colorspace Gray" 
     #parameters << "-sharpen 0x1" 
     #parameters << "-type grayscale" 
     #parameters << "-contrast-stretch 0" 
     #parameters << "-clone 0" 
     #parameters << "-deskew 40%" 
     parameters << ":dest" 

     parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") 

     success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path)) 
     rescue PaperclipCommandLineError => e 
     raise PaperclipError, "There was an error during the grayscale conversion for #{@basename}" if @whiny 
     end 

     dst 
    end 

    end 
end 
+1

你嘗試過什麼?它有助於向我們展示你的嘗試,所以我們告訴你是否正確地做了這件事。 –

回答

0

使用我回形針能添加文本清潔處理器。我添加它作爲一個風格經模型:

has_attached_file :file, :styles => { :clean => { :processors => [:text_cleaner] } } 

而在/lib/paperclip_processors/text_cleaner.rb我:

module Paperclip 
    # Handles grayscale conversion of images that are uploaded. 
    class TextCleaner < Processor 

    def initialize file, options = {}, attachment = nil 
     super 
     @format = File.extname(@file.path) 
     @basename = File.basename(@file.path, @format) 
    end 

    def make 
     src = @file 
     dst = Tempfile.new([@basename,@format]) 

     dst.binmode 

     begin 
     parameters = '-respect-parenthesis \(:source -colorspace gray -type grayscale -contrast-stretch 0 \) \(-clone 0 -colorspace gray -negate -lat 15x15+5% -contrast-stretch 0 \) -compose copy_opacity -composite -fill "white" -opaque none +matte -deskew 40% -auto-orient -sharpen 0x1 :dest' 
     success = Paperclip.run('convert', parameters, :source => File.expand_path(@file.path), :dest => File.expand_path(dst.path)) 
     rescue PaperclipCommandLineError => e 
     raise PaperclipError, "There was an error during the textclean conversion for #{@basename}" if @whiny 
     end 

     dst 
    end 

    end 
end