|
|
画像から顔を検出する
webサービスを利用して,ファイルまたはURLを指定して,jpg/pngから顔を検出する.
code
detectface.py←右クリックで保存できます.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib
import urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
from BeautifulSoup import BeautifulSoup
import json
def eyeinfo(soup):
return {'x':int(soup['x']), 'y':int(soup['y'])}
def featuresinfo(soup):
features = {}
features['s-avg'] = float(soup['s-avg'])
features['s-min'] = float(soup['s-min'])
features['s-max'] = float(soup['s-max'])
f = {}
soup = soup.findAll('point')
for point in soup:
f[point['id']] = {'x':int(point['x']), 'y':int(point['y']), 's':float(point['s'])}
features['point'] = f
return features
def faceinfo( xml ):
soup = BeautifulSoup( xml )
faces = soup.findAll('face')
info = []
for face in faces:
fi = {}
try:
bounds = {'x':int(face.bounds['x']), 'y':int(face.bounds['y']), 'width':int(face.bounds['width']), 'height':int(face.bounds['height'])}
fi['bounds'] = bounds
except:
fi['bounds'] = ''
try:
fi['right-eye'] = eyeinfo( face.find('right-eye') )
except:
fi['right-eye'] = ''
try:
fi['left-eye'] = eyeinfo( face.find('left-eye') )
except:
fi['left-eye'] = ''
try:
fi['features'] = featuresinfo( face.find('features') )
except:
fi['features'] = ''
fi['powered by'] = 'http://detectface.com/'
info.append(fi)
return info
def detectface_url( imgurl, m=0, f=0 ):
url = 'http://detectface.com/api/detect?m=%d&f=%d&url=%s' % (m, f, urllib.quote(imgurl) )
try:
xml = urllib.urlopen( url ).read()
info = faceinfo( xml )
except:
info = ''
return info
def detectface_file( imgfilename, m=0, f=0 ):
url = 'http://detectface.com/api/detect?m=%d&f=%d' % (m, f)
register_openers()
info = ''
with open(imgfilename, "rb") as f:
datagen, headers = multipart_encode({"file": f})
request = urllib2.Request(url, datagen, headers)
response = urllib2.urlopen(request)
xml = response.read()
info = faceinfo( xml )
return info
########################################################################
if __name__ == '__main__':
info = detectface_file('face.jpg')
print json.dumps( info, indent=2 )
info = detectface_url('http://face.com/face.jpg')
print json.dumps( info, indent=2 )
参考URL
|