编写下载图片脚本
# -*- encoding: utf-8 -*-
import urllib2
import os
def save_img(img_url,file_name,file_path='img'):
#保存图片到磁盘文件夹 file_path中,默认为当前脚本运行目录下的 book\img文件夹
try:
if not os.path.exists(file_path):
print '文件夹',file_path,'不存在,重新建立'
#os.mkdir(file_path)
os.makedirs(file_path)
#获得图片后缀
if 'jpeg' in img_url:
file_suffix = '.jpeg'
elif 'jpg' in img_url:
file_suffix = '.jpg'
elif 'png' in img_url:
file_suffix = '.png'
else:
file_suffix = '.jpeg'
#拼接图片名(包含路径)
filename = '{}{}{}{}'.format(file_path,os.path.sep,file_name,file_suffix)
#下载图片,并保存到文件夹中
response = urllib2.urlopen(img_url)
cat_img = response.read()
with open(filename, 'wb') as f:
f.write(cat_img)
except IOError as e:
print '文件操作失败',e
except Exception as e:
print '错误 :',e
save_img('https://mmbiz.qlogo.cn/mmbiz_png/NGEiao2Vd8N7wpsu2hKz4zWBuWUIkAl9WsPLNicnRYkUGBrcV7suAFFdRqCxOs7sR46Lr58HttWOfhzKmGvRRo3A/0?wx_fmt=png', '15');
然后批量分割使用 dlib库
# Author: jiangguangxun
# Dlib: http://dlib.net/
# Blog: http://www.cnblogs.com/AdaminXie/
# Github: https://github.com/coneypo/Dlib_examples
# create object of OpenCv
# use OpenCv to read and show images
import dlib
import cv2
detector = dlib.get_frontal_face_detector()
# read image
img = cv2.imread("img/5.jpeg")
# use detector of Dlib to detector faces
faces = detector(img, 1)
print("Faces in all: ", len(faces))
# Traversal every face
for i, d in enumerate(faces):
print("no", i+1, "face:",
"left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
crop_img= img[d.top():d.bottom(),d.left():d.right()]
cv2.namedWindow("img", 2)
cv2.imwrite(str(21+i)+".jpg", crop_img, [int(cv2.IMWRITE_JPEG_QUALITY),95])
# cv2.imshow("img",crop_img)
# cv2.waitKey(0)
作者:蒋光洵