TensorFlow识别复杂验证码以及搭建生产环境(8)—— 基于Python的调用

0x00 基本环境

grpc, tensorflow-serving-client 都要装好

0x01 client.py

import sys
sys.path.insert(0, "./")
from tensorflow_serving_client.protos import predict_pb2, prediction_service_pb2
# import cv2
from grpc.beta import implementations
import tensorflow as tf
from tensorflow.python.framework import dtypes
import time
from PIL import Image
import numpy as np


def convert2gray(img):
    if len(img.shape) > 2:
        gray = np.mean(img, -1)
        # 上面的转法较快,正规转法如下
        # r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
        # gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
        # int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);
        return gray
    else:
        return img

#注意,如果在windows下测试,文件名可能需要写成:im_name = r"测试文件目录\文件名"
if __name__ == '__main__':
    #文件读取和处理
    # im = cv2.imread(im_name)
    # re_im = cv2.resize(im, (224, 224), interpolation=cv2.INTER_CUBIC)

    captcha_image = Image.open('D:\\jwxt\\new_test\\4am7.jpg')
    captcha_image = np.array(captcha_image)
    captcha_image = convert2gray(captcha_image)
    captcha_image = captcha_image.flatten() / 255
    #记个时
    start_time = time.time()
    #建立连接
    channel = implementations.insecure_channel("192.168.190.128", 9000)
    stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
    request = predict_pb2.PredictRequest()
    #这里由保存和运行时定义,第一个是运行时配置的模型名,第二个是保存时输入的方法名
    request.model_spec.name = "crack_captcha"
    #入参参照入参定义
    request.inputs["image"].ParseFromString(tf.contrib.util.make_tensor_proto(captcha_image, dtype=dtypes.float32, shape=[1, 60, 180, 1]).SerializeToString())
    #第二个参数是最大等待时间,因为这里是block模式访问的
    response = stub.Predict(request, 40.0)
    results = {}
    for key in response.outputs:
        tensor_proto = response.outputs[key]
        nd_array = tf.contrib.util.make_ndarray(tensor_proto)
        results[key] = nd_array
    #print("cost %ss to predict: " % (time.time() - start_time))
    tmp = ''
    for i in results['out']:
        # print(i)
        if i < 10:
            char_code = i + ord('0')
        elif i < 36:
            char_code = i - 10 + ord('a')
        tmp = tmp + chr(char_code)
    print(tmp)

0x02 输出

4am7

0x03 扩展

在其他的地方(例如说是网站后台)使用方式跟以上非常相似。
例如说在我写的基于Django写的网站为例:
将上述的文件改写成:

from PIL import Image
import numpy as np
import time
from grpc.beta import implementations
from tensorflow_serving_client.protos import predict_pb2, prediction_service_pb2
import tensorflow as tf
from tensorflow.python.framework import dtypes

def convert2gray(img):
    if len(img.shape) > 2:
        gray = np.mean(img, -1)
        # 上面的转法较快,正规转法如下
        # r, g, b = img[:,:,0], img[:,:,1], img[:,:,2]
        # gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
        # int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);
        return gray
    else:
        return img

def crack_jwxt_captcha(file_name):
    #文件读取和处理
    # im = cv2.imread(im_name)
    # re_im = cv2.resize(im, (224, 224), interpolation=cv2.INTER_CUBIC)

    captcha_image = Image.open(file_name)
    captcha_image = np.array(captcha_image)
    captcha_image = convert2gray(captcha_image)
    captcha_image = captcha_image.flatten() / 255
    #记个时
    start_time = time.time()
    #建立连接
    channel = implementations.insecure_channel("192.168.190.128", 9000)
    stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
    request = predict_pb2.PredictRequest()
    #这里由保存和运行时定义,第一个是运行时配置的模型名,第二个是保存时输入的方法名
    request.model_spec.name = "crack_captcha"
    #入参参照入参定义
    request.inputs["image"].ParseFromString(tf.contrib.util.make_tensor_proto(captcha_image, dtype=dtypes.float32, shape=[1, 60, 180, 1]).SerializeToString())
    #第二个参数是最大等待时间,因为这里是block模式访问的
    response = stub.Predict(request, 40.0)
    results = {}
    for key in response.outputs:
        tensor_proto = response.outputs[key]
        nd_array = tf.contrib.util.make_ndarray(tensor_proto)
        results[key] = nd_array
    print("cost %ss to predict: " % (time.time() - start_time))
    tmp = ''
    for i in results['out']:
        print(i)
        if i < 10:
            char_code = i + ord('0')
        elif i < 36:
            char_code = i - 10 + ord('a')
        tmp = tmp + chr(char_code)
    return tmp

这样就能很方便的被其他模块调用

在控制器这块这么写就行

@csrf_exempt
def upload_jwxt_captcha(req):
    if req.method == 'POST':
        image = req.FILES.get('image', None)
        if not image:
            result = {'rst': -2, 'msg': '文件上传失败'}
        else:
            import time
            file_name = str(int(time.time() * 1000000)) + '.jpg'
            destination = open(os.path.join("./upload", file_name), 'wb+')
            for chunk in image.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()

            result = {'rst': 0, 'msg': 'ok', 'data': crack_jwxt_captcha("./upload/" + file_name)}
        return HttpResponse(json.dumps(result), content_type="application/json")
    else:
        result = {'rst': -1, 'msg': '当前请求不支持GET方式'}
        return HttpResponse(json.dumps(result), content_type="application/json")

这样网页服务器就能收到验证码图片,然后返回识别出来的图片。
TensorFlow识别复杂验证码以及搭建生产环境(8)—— 基于Python的调用_第1张图片
TensorFlow识别复杂验证码以及搭建生产环境(8)—— 基于Python的调用_第2张图片

你可能感兴趣的:(tensorflow)