御命丹心

萧瑟悲声秋风起,刹忆寒蝉未鸣时

导航

图片识别

# 获取图片中像素点数量最多的像素
def get_threshold(image):
    pixel_dict = defaultdict(int)
    #image = '..\exceptionpictures\%s\%s.png' % (path, img_name)
    # 像素及该像素出现次数的字典
    rows, cols = image.size
    for i in range(rows):
        for j in range(cols):
            pixel = image.getpixel((i, j))
            pixel_dict[pixel] += 1

    count_max = max(pixel_dict.values()) # 获取像素出现出多的次数
    pixel_dict_reverse = {v:k for k,v in pixel_dict.items()}
    threshold = pixel_dict_reverse[count_max] # 获取出现次数最多的像素点
    return threshold

# 按照阈值进行二值化处理
# threshold: 像素阈值
def get_bin_table(threshold):
    # 获取灰度转二值的映射table
    table = []
    for i in range(256):
        rate = 0.1 # 在threshold的适当范围内进行处理
        if threshold*(1-rate)<= i <= threshold*(1+rate):
            table.append(1)
        else:
            table.append(0)
    return table

# 去掉二值化处理后的图片中的噪声点
def cut_noise(image):

    rows, cols = image.size # 图片的宽度和高度
    change_pos = [] # 记录噪声点位置

    # 遍历图片中的每个点,除掉边缘
    for i in range(1, rows-1):
        for j in range(1, cols-1):
            # pixel_set用来记录该店附近的黑色像素的数量
            pixel_set = []
            # 取该点的邻域为以该点为中心的九宫格
            for m in range(i-1, i+2):
                for n in range(j-1, j+2):
                    if image.getpixel((m, n)) != 1: # 1为白色,0位黑色
                        pixel_set.append(image.getpixel((m, n)))

            # 如果该位置的九宫内的黑色数量小于等于4,则判断为噪声
            if len(pixel_set) <= 4:
                change_pos.append((i,j))

    # 对相应位置进行像素修改,将噪声处的像素置为1(白色)
    for pos in change_pos:
        image.putpixel(pos, 1)
    return image # 返回修改后的图片

# 识别图片中的数字加字母
# 传入参数为图片路径,返回结果为:识别结果
def OCR_lmg(img_path):
    #img_path = '..\exceptionpictures\%s\%s.png' % (path, img_name)
    image = Image.open(img_path) # 打开图片文件
    imgry = image.convert('L')  # 转化为灰度图
    # 获取图片中的出现次数最多的像素,即为该图片的背景
    max_pixel = get_threshold(imgry)
    # 将图片进行二值化处理
    table = get_bin_table(threshold=max_pixel)
    out = imgry.point(table, '1')
    # 去掉图片中的噪声(孤立点)
    out = cut_noise(out)
    #保存图片
    # out.save('E://figures/img_gray.jpg')
    # 仅识别图片中的数字
    #text = pytesseract.image_to_string(out, config='digits')
    # 识别图片中的数字和字母
    text = pytesseract.image_to_string(out)
    # 去掉识别结果中的特殊字符
    exclude_char_list = ' .:\\|\'\"?![],()~@#$%^&*_+-={};<>/¥'
    text = ''.join([x for x in text if x not in exclude_char_list])
    #print(text)
    return text

# 识别指定文件目录下的图片
def main(value):
    print(("遍历路径为..\exceptionpictures\\%s下的所有png/jpg图片中...")%(value))
    # 识别指定文件目录下的图片
    # 图片存放目录figures
    #dir = img_path
    dir = '..\exceptionpictures\\%s'%(value)
    correct_count = 0  # 图片总数
    total_count = 0    # 识别正确的图片数量
    # 遍历figures下的png,jpg文件
    for file in os.listdir(dir):
        if file.endswith('.png') or file.endswith('.jpg'):
            # print(file)
            image_path = '%s/%s'%(dir,file) # 图片路径
            answer = file.split('.')[0]  # 图片名称,即图片中的正确文字
            recognizition = OCR_lmg(image_path) # 图片识别的文字结果
            print(answer)
            #print(recognizition)
            if recognizition == answer: # 如果识别结果正确,则total_count加1
                correct_count += 1
            total_count += 1
    print('图片总数: %d, 识别的图片数量: %d'%(total_count, correct_count))

'''
#识别图片中中文字体
def chi_sim(path,img_name,value):
    try:
        print("获取图片成功...识别中....")
        img_path = '..\exceptionpictures\%s\%s.png'%(path,img_name)
        text = pytesseract.image_to_string(Image.open(img_path),lang='chi_sim').strip()
        print('识别结果为:' + text)
        try:
            assert(text) == value
            print("识别验证提示信息正确")
        except:
            print("识别验证提示信息错误")
    except Exception as e:
        raise e
'''

#批量图片二值化
def all_createFile(path):
    try:
        input_dir = '../exceptionpictures/%s/'%(path)   #输入文件夹
        out_dir = '../exceptionpictures/%s/'%(path)     #输出文件夹
        a = os.listdir(input_dir)
        for i in a:
            print(i)
            I = Image.open(input_dir + i)
            L = I.convert('L')
            L.save(out_dir + i)
            print("图片二值化成功")
    except Exception as e:
        print(e)

#图片批量放大
def all_ResizeImage(path):
    try:
        input_dir = '../exceptionpictures/%s/'%(path)   #输入文件夹
        out_dir = '../exceptionpictures/%s/'%(path)     #输出文件夹
        size_m = 300
        size_n = 120
        a = os.listdir(input_dir)
        for i in a:
            print(i)
            I = Image.open(input_dir + i)
            L = I.resize((size_m, size_n),Image.ANTIALIAS)
            L.save(out_dir + i)
            print("图片放大比例300:120成功")
    except Exception as e:
        print(e)

 

posted on 2020-07-10 19:32  正法  阅读(302)  评论(0编辑  收藏  举报