Base64是网络上最常见的用于传输字节码的编码方式之一,可用于在HTTP环境下传递较长的信息。如果要通过Http调用tensorflow服务完成图像分类或者检测等任务,就需要用base64来传递图像信息。tensorflow也提供了函数decode_base64来解析图像。
tensorflow decode_base64函数的使用方法如下:
def base64_decode_img(b64code): """ :param b64code:输入为图像的base64编码字符串 :return: """ base64_tensor = tf.convert_to_tensor(b64code, dtype=tf.string) img_str = tf.decode_base64(base64_tensor) #得到(width, height, channel)的图像tensor img = tf.image.decode_image(img_str, channels=3) with tf.Session() as sess: img_value = sess.run([img])[0] #得到numpy array类型的数据 print(img_value.shape)
使用decode_base64有可能会遇到invalid character
的异常。这是因为decode_base64要求输入是web-safe的base64编码,编码后的字符串中不应该有+
或者/
。下面这段代码是decode_base64的函数声明:
def decode_base64(input, name=None): r"""Decode web-safe base64-encoded strings. Input may or may not have padding at the end. See EncodeBase64 for padding. Web-safe means that input must use - and _ instead of + and /.
python语言可以用base64.urlsafe_b64encode
函数代替base64.b64encode
来生成web-safe的base64字符串。
def base64_encode_img(img): """ :param img: :return: """ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) print('shape of img_rgb:', img_rgb.shape) pil_img = Image.fromarray(img_rgb) buf = cStringIO.StringIO() pil_img.save(buf, format="JPEG", quality=100) b64code = base64.urlsafe_b64encode(buf.getvalue()) #web-safe # b64code = base64.b64encode('abcdefgdisoaufd,0.342,0.456,0.987') # not web-safe return b64code