声明
此处除了一些调用方法,我还加了一部分其他处理,酌情选用,适当调整.
代码
import time
import requests
import base64
import numpy as np
from json import JSONDecoder
import cv2
# face++ 调用抠图接口地址
http_url = "https://api-cn.faceplusplus.com/humanbodypp/v2/segment"
# 验证用 key 和 secret
key = "***"
secret = "***"
# 测试用图片地址(文件夹)
file_name = '../Asserts/images/test.jpg'
def img_base64(img_path):
"""
图片转base64
:param img_path:
:return:
"""
with open(img_path, "rb") as f:
# b64encode是编码,b64decode是解码
# base64.b64decode(base64data)
base64_str = base64.b64encode(f.read())
f.close()
return base64_str
def base64_mat(base64_str):
"""
base64转opencv图片
cv2.IMREAD_UNCHANGED 读取结果为图片本身维度,如透明图为4通道,彩色三通道,黑白单通道
:param base64_str: 注意,这里会解析成原图样式
:return:
"""
img_data = base64.b64decode(base64_str)
img_nparr = np.fromstring(img_data, np.uint8)
img_mat = cv2.imdecode(img_nparr, cv2.IMREAD_UNCHANGED)
return img_mat
def mat_base64(img_path):
"""
base64转opencv图片
:param img_path:
:return:
"""
img_mat = cv2.imread(img_path, cv2.IMREAD_COLOR)
img_code = cv2.imencode('.jpg', img_mat)[1]
base64_str = base64.b64encode(img_code).decode()
return base64_str
# if __name__ == '__main__':
# # 测试文件转base64
# base64_str = mat_base64(file_name)
# print(base64_str)
# # 测试base64转mat图像
# img_mat = base64_mat(base64_str)
# cv2.imshow("the result:", img_mat)
# cv2.waitKey(0)
# 测试主函数
if __name__ == '__main__':
start_time = time.time()
print('开始时间计时:', start_time)
# 要发送的数据
data = {"api_key": key, # key
"api_secret": secret, # secret
"return_grayscale": "0" # 0=仅图像 1=图像+灰度图 2=仅灰度图
}
# 读取图片文件(注意 r 和 rb 的区别)
file_data = open(file_name, "rb")
files = {"image_file": file_data}
# post进行发送
response = requests.post(http_url, data=data, files=files)
# 获取反馈并解析
req_con = response.content.decode('utf-8')
# 记得关闭文件流
file_data.close()
req_dict = JSONDecoder().decode(req_con)
print('请求ID:', req_dict[u'request_id'])
print('请求用时:', req_dict[u'time_used'])
# print('灰度图-base64:', req_dict[u'result'])
# print('图像-base64:', req_dict[u'body_image'])
# print('失败信息:', req_dict[u'error_message'])
try: # 正常情况下,输出图像
# print('图像-base64:', req_dict[u'body_image'])
base64_str = req_dict[u'body_image']
img_mat = base64_mat(base64_str)
# b_img = img_mat[:, :, 0] # B通道
# g_img = img_mat[:, :, 1] # G通道
# r_img = img_mat[:, :, 2] # R通道
# a_img = img_mat[:, :, 3] # A通道
b, g, r, a = cv2.split(img_mat)
# cv2.imshow("b", b)
# cv2.imshow("g", g)
# cv2.imshow("r", r)
# cv2.imshow("a", a)
# cv2.waitKey()
# 合并前三通道做原图,用透明通道抠图
img_chanel3 = cv2.merge([b, g, r])
img_ext = cv2.add(img_chanel3, np.zeros(np.shape(img_chanel3), dtype=np.uint8), mask=a)
# 留a通道做mask
img_mask = a
cv2.imshow("the EXTRACTION result", img_ext)
cv2.imshow("the MASK result", img_mask)
cv2.waitKey()
except KeyError: # 异常情况下,打印异常
print('失败信息:', req_dict[u'error_message'])
end_time = time.time()
print('结束时间计时:{}, 系统运行总耗时:{}'.format(start_time, end_time-start_time) )