用 Face.com API 处理肖像照

之前某天, 我接了个任务: 把用户上传的照片(全身或者半身照)做处理, 输出一张从头到肩的肖像. 一开始我觉得很难, 因为高等数学什么的早就还给老师了. 但后来一想, “Not to re-invent the wheel”, 找个现成的脸部识别 API 不就可以了吗.

于是开始 Google “face detection”. 结果之中, 来自 face.com 的 API 帮我搞定了这个任务. 顺便把一个批处理的 ruby 程序贴上, 尽管写的很丑.

require 'rubygems'
require 'net/http'
require 'rest_client'
require 'json'

ratio = 2.0
photos = Dir.glob File.join("photos", "*.jpg")
photos.each { |photo| puts photo

    res = RestClient.post( 'http://api.face.com/faces/detect.json',
      :api_key => 'your api key',
      :api_secret => 'your api secret',
      :filename => File.new(photo, 'rb')
    )
    filename = File.basename(photo)
    dirname = File.dirname(photo)
    thumb_name = dirname + '/thumbs/100x120_' + filename
    #puts res
    result = JSON.parse res
    #puts result['status']
    if result['status'] == 'success'
        width = result['photos'][0]['width']
        height = result['photos'][0]['height']
        tag_width = (result['photos'][0]['tags'][0]['width'] * width / 100).to_i
        center_x = (result['photos'][0]['tags'][0]['center']['x'] * width / 100).to_i
        center_y = (result['photos'][0]['tags'][0]['center']['y'] * height / 100).to_i
        portrait_left = ( center_x - ( tag_width / 2 * ratio )).to_i
        portrait_left = 0 if portrait_left < 0
        portrait_top = ( center_y - ( tag_width / 2 * ratio )).to_i
        portrait_top = 0 if portrait_top < 0
        portrait_width = ( tag_width * ratio ).to_i
        portrait_height = ( portrait_width * 1.2 ).to_i
        puts portrait_left, portrait_top, portrait_width, portrait_height

        `convert -crop '#{portrait_width}x#{portrait_height}+#{portrait_left}+#{portrait_top}' -resize '100x120' '#{photo}' '#{thumb_name}'`
    end
}

处理结果:

另外还有个传闻: facebook.com 要收购 face.com. 我心里想, 那把 book.com 也收了吧? 😀

Leave a Reply

Your email address will not be published. Required fields are marked *