hellokuls / cnnyzm

用CNN识别验证码| python识别验证码| 训练验证码模型
Apache License 2.0
194 stars 44 forks source link

第一次请求正常 再次请求就报错 #6

Closed JxiaoC closed 2 years ago

JxiaoC commented 2 years ago

验证的时候, 第二次请求就出现Original stack trace for 'save1/RestoreV2' 这样的错误提示, 每次请求save*就会+1, 如果是重新运行python文件, 就正常

尝试过在with tf.Session() as sess:下面增加sess.run(tf.compat.v1.global_variables_initializer()), 虽然这样是不报错了...但是只有第一次返回的是正确的验证码, 接下来都是错误的验证码...

初学者...希望能指点指点

import base64
import json
import os

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from cPython import cPython as cp
from train import cnn_graph
from PIL import Image
from process import vec2text,convert2gray,wrap_gen_captcha_text_and_image_test
from getimg import CAPTCHA_HEIGHT, CAPTCHA_WIDTH, CAPTCHA_LEN, CAPTCHA_LIST

import numpy as np
import random

# 验证码图片转化为文本
def captcha2text(image_list, height=CAPTCHA_HEIGHT, width=CAPTCHA_WIDTH):
    x = tf.placeholder(tf.float32, [None, height * width])
    keep_prob = tf.placeholder(tf.float32)
    y_conv = cnn_graph(x, keep_prob, (height, width))
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, tf.train.latest_checkpoint('.'))
        predict = tf.argmax(tf.reshape(y_conv, [-1, CAPTCHA_LEN, len(CAPTCHA_LIST)]), 2)
        vector_list = sess.run(predict, feed_dict={x: image_list, keep_prob: 1})
        vector_list = vector_list.tolist()

        text_list = [vec2text(vector) for vector in vector_list]

        return text_list

if __name__ == '__main__':
    data = json.loads(cp.get_html('http://whois.chinaz.com/ajaxsync.aspx?at=vc&%s' % random.random()))
    image = base64.b64decode(data['Img'].replace('data:image/jpeg;base64,', ''))
    with open('temp.jpg', 'wb') as w:
        w.write(image)
    image_a = Image.open('temp.jpg')
    img_array = np.array(image_a)
    image = convert2gray(img_array)
    image = image.flatten() / 255
    pre_text = captcha2text([image])
    print(pre_text)

    data = json.loads(cp.get_html('http://whois.chinaz.com/ajaxsync.aspx?at=vc&%s' % random.random()))
    image = base64.b64decode(data['Img'].replace('data:image/jpeg;base64,', ''))
    with open('temp2.jpg', 'wb') as w:
        w.write(image)
    image_a = Image.open('temp2.jpg')
    img_array = np.array(image_a)
    image = convert2gray(img_array)
    image = image.flatten() / 255
    pre_text = captcha2text([image])
    print(pre_text)
JxiaoC commented 2 years ago

解决了..

    with tf.Session() as sess:
        saver.restore(sess, tf.train.latest_checkpoint('.'))
        predict = tf.argmax(tf.reshape(y_conv, [-1, CAPTCHA_LEN, len(CAPTCHA_LIST)]), 2)
        vector_list = sess.run(predict, feed_dict={x: image_list, keep_prob: 1})
        vector_list = vector_list.tolist()

        text_list = [vec2text(vector) for vector in vector_list]
    tf.reset_default_graph() # 在with 外执行reset_default_graph重置操作
    return text_list