标签:border 服务 write redirect similar append _for 图像 log
@
你好! python flask图片识别系统使用到的技术有:图片背景切割、图片格式转换(pdf转png)、图片模板匹配、图片区别标识。
第一组:
图片1:
图片2:
开始上传:
上传成功、图片预览:
(emmm..抱歉图片大小未处理,有点大哈)
识别效果:
成功了。。。
第二组:
这会搞个复杂些的,也是实用的图片
图片1:(图片仅供交流,侵权删)
图片2:
你会发现,其实图片2是图片1的子图,这下我们看看程序处理的效果:
还可以哈,截取了图片1中的匹配部分,然后标识出来了区别
图片背景切割
from PIL import Image
import cv2
import os
from common.util import Util
# 图片去除周围白色
def img_cut_white(img_path, cut_img_path, tagrt_rgb_x, tagrt_rgb_y):
# img_path = "./images/notebook.png"
img = Image.open(img_path)
rgb_im = img.convert(‘RGB‘)
width, height = img.size
# 打印图片的宽高
print(width, height)
# 把高度分为8份,后续用这8个点高度作为高度循环
list_target_height = [height / 8, height / 4, 3 * height / 8, height / 2, 5 * height / 8, 3 * height / 4]
x0,x1 = get_pointx(bypara="1",width=width,height=height,list_target_height=list_target_height,rgb_im=rgb_im,tagrt_rgb=tagrt_rgb_x)
y0, y1 = get_pointx(bypara="2", width=width, height=height, list_target_height=list_target_height, rgb_im=rgb_im,
tagrt_rgb=tagrt_rgb_y)
print(x0, x1)
print(y0, y1)
# 按照两个对角像素点切割图片
Util().cut_img_by_point(img_path=img_path,x0=x0,x1=x1,y0=y0,y1=y1,cut_img_path=cut_img_path)
# 获取x0,x1,y0,y1
def get_pointx(bypara=None,width=None,height=None,list_target_height=None,rgb_im=None,tagrt_rgb=None):
‘‘‘
:param bypara: 1代表进行获取x0,x1的逻辑,2代表进行获取y0,y1的逻辑
:param width: 图片宽度
:param height: 图片高度
:param list_target_height:
:param rgb_im: 转换为“RGB”通道的图片
:param tagrt_rgb: rgb突变范围值
:return:
‘‘‘
x0 = 0
x1 = 0
y0 = 0
y1 = 0
# 多个目标高度,每个像素点的rgb之和
multi_point_rgb_sum = 0
# 多个目标高度像素点的所有像素点rgb总和的平均值
list_rgb_sum_avg = []
if bypara == ‘1‘:
for i in range(width):
for j in range(len(list_target_height)):
# print("i:",i)
# print("list_target_height[j]:",list_target_height[j])
r, g, b = rgb_im.getpixel((i, list_target_height[j]))
# 一个点的rgb和
point_sum = r + g + b
multi_point_rgb_sum += point_sum
# print(point_sum, multi_point_rgb_sum)
list_rgb_sum_avg.append(multi_point_rgb_sum / 6)
multi_point_rgb_sum = 0
# 与白色背景图像的差值list
list_white_sub = get_listwhitesub(list_rgb_sum_avg)
list_white_sub_dup = list_white_sub.copy()
list_white_sub.reverse()
# 获得x0
for i in range(len(list_white_sub_dup)):
if list_white_sub_dup[i] > tagrt_rgb:
x0 = i
break
# 获得x1
for i in range(len(list_white_sub)):
# print(list_white_sub[i])
if list_white_sub[i] > tagrt_rgb:
x1 = (width - i)
break
return x0, x1
elif bypara == ‘2‘:
for i in range(height):
for j in range(width):
r, g, b = rgb_im.getpixel((j, i))
# r, g, b = rgb_im.getpixel(j, i)
# 一个点的rgb和
point_sum = r + g + b
multi_point_rgb_sum += point_sum
# print(point_sum, multi_point_rgb_sum)
list_rgb_sum_avg.append(multi_point_rgb_sum / width)
multi_point_rgb_sum = 0
# 与白色背景图像的差值list
list_white_sub = get_listwhitesub(list_rgb_sum_avg)
list_white_sub_dup = list_white_sub.copy()
list_white_sub.reverse()
# 获得y0
for i in range(len(list_white_sub_dup)):
if list_white_sub_dup[i] > tagrt_rgb:
y0 = i
break
# 获得y1
for i in range(len(list_white_sub)):
# print(list_white_sub[i])
if list_white_sub[i] > tagrt_rgb:
y1 = (height - i)
break
return y0, y1
# 获得list中相邻元素的差值list
def get_listsub(list2):
list3 = []
for i in range(len(list2)):
if i <= len(list2) - 2:
cha = list2[i + 1] - list2[i]
list3.append(abs(cha))
return list3
# 与白色rgb的差值 list
def get_listwhitesub(list2):
list3 = []
for i in range(len(list2)):
print(abs(list2[i]-765))
list3.append(abs(list2[i]-765))
return list3
if __name__=="__main__":
# img_path = "./images/notebook.png"
# cut_img_path = ‘./images/notebookcut4.png‘
tagrt_rgb_x = 300
tagrt_rgb_y = 10
# tagrt_rgb_x = 180
# tagrt_rgb_y = 180
# img_path = "../images/UIyuantu.png"
# cut_img_path = ‘../images/yuantucut0.png‘
# img_path = "../images/00.png"
img_path = "IMG_0.jpg"
cut_img_path = ‘IMG_0_cut.jpg‘
img_cut_white(img_path, cut_img_path, tagrt_rgb_x, tagrt_rgb_y)
pdf转png代码:
import fitz
import os
import datetime
from common.util import Util
from pdf2image import convert_from_path,convert_from_bytes
def pyMuPDF_fitz(pdfPath, imagePath):
startTime_pdf2img = datetime.datetime.now() # 开始时间
# print("imagePath=" + imagePath)
# pdfDoc = fitz.open(pdfPath)
# print(pdfPath)
images = convert_from_path(pdfPath)
for index, img in enumerate(images):
# for pg in range(pdfDoc.pageCount):
# page = pdfDoc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。
# 此处若是不做设置,默认图片大小为:792X612, dpi=96
zoom_x = 1.33333333 # (1.33333333-->1056x816) (2-->1584x1224)
zoom_y = 1.33333333
# zoom_x = 1 # (1.33333333-->1056x816) (2-->1584x1224)
# zoom_y = 1
# mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
# pix = img.getPixmap(matrix=mat, alpha=False)
# img.save(‘%s/page_%s.png‘ % (outputDir, index))
if not os.path.exists(imagePath): # 判断存放图片的文件夹是否存在
os.makedirs(imagePath) # 若图片文件夹不存在就创建
img.save(imagePath + ‘/‘ + ‘images_%s.png‘ % index)
# pix.writePNG(imagePath + ‘/‘ + ‘images_%s.png‘ % index) # 将图片写入指定的文件夹内
endTime_pdf2img = datetime.datetime.now() # 结束时间
# print(‘pdf2img时间=‘, (endTime_pdf2img - startTime_pdf2img).seconds)
def single_pyMuPDF_fitz(pdfPath, imagePath):
startTime_pdf2img = datetime.datetime.now() # 开始时间
# print("imagePath=" + imagePath)
# pdfDoc = fitz.open(pdfPath)
images = convert_from_path(pdfPath)
for index, img in enumerate(images):
# page = pdfDoc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。
# 此处若是不做设置,默认图片大小为:792X612, dpi=96
zoom_x = 1.33333333 # (1.33333333-->1056x816) (2-->1584x1224)
zoom_y = 1.33333333
# zoom_x = 1 # (1.33333333-->1056x816) (2-->1584x1224)
# zoom_y = 1
# mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
# pix = img.getPixmap(matrix=mat, alpha=False)
# pix.writePNG(imagePath) # 将图片写入指定的文件夹内
img.save(imagePath)
endTime_pdf2img = datetime.datetime.now() # 结束时间
# print(‘pdf2img时间=‘, (endTime_pdf2img - startTime_pdf2img).seconds)
if __name__ == "__main__":
# pdfPath = ‘../images/EWSC007.pdf‘
pdfPath = ‘SCAN855.PDF‘
##随机文件夹名字
imagePath = ‘SCAN855.png‘
# imagePath = ‘../images/image‘+str(Util().random_num())+‘.png‘
# imagePath = ‘../images/SCAN003.PDF‘
single_pyMuPDF_fitz(pdfPath, imagePath)
# # 遍历文件夹下所有文件
# work_dir = imagePath
# for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
# for filename in filenames:
# file_path = os.path.join(parent, filename)
# print(‘文件名:%s‘ % filename)
# print(‘文件完整路径:%s\n‘ % file_path)
图片比较不同:
# import the necessary packages
from skimage.measure import compare_ssim
import argparse
import imutils
import cv2
def get_img_result(path1, path2, path3, path4):
# construct the argument parse and parse the arguments
# ap = argparse.ArgumentParser()
# ap.add_argument("-f", "--first", required=True,
# help="first input image")
# ap.add_argument("-s", "--second", required=True,
# help="second")
# args = vars(ap.parse_args())
# load the two input images
imageA = cv2.imread(path1)
imageB = cv2.imread(path2)
# convert the images to grayscale
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
# compute the Structural Similarity Index (SSIM) between the two
# images, ensuring that the difference image is returned
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
print("SSIM: {}".format(score))
# threshold the difference image, followed by finding contours to
# obtain the regions of the two input images that differ
thresh = cv2.threshold(diff, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# loop over the contours
for c in cnts:
# compute the bounding box of the contour and then draw the
# bounding box on both input images to represent where the two
# images differ
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
# show the output images
# cv2.imshow("Original", imageA)
cv2.imwrite(path3, imageA)
# cv2.imshow("Modified", imageB)
cv2.imwrite(path4, imageB)
# cv2.imshow("Diff", diff)
# cv2.imshow("Thresh", thresh)
# cv2.waitKey(0)
if __name__==‘__main__‘:
get_img_result(‘static/images/modified_03.png‘, ‘static/images/original_03.png‘, ‘static/images/test1.png‘, ‘static/images/test2.png‘)
flask路由部分:
from flask import Flask, redirect, url_for, jsonify
import base64
from flask import request
import os
from flask import render_template
from basicclass import image_diff
import time
from datetime import timedelta
from werkzeug.utils import secure_filename
from common.image_util import random_num
from basicclass.pdfconvertpng import pyMuPDF_fitz, single_pyMuPDF_fitz
from common.util import Util
from basicclass.autocutpic import img_cut_white
from basicclass.teamplatemath import match_target
from common.globalparam import tagrt_rgb_x, tagrt_rgb_y, host_ip, port
from basicclass.imagediff import dif_two_pic,dif_mark
from basicclass.image_diff import get_img_result
import os
import shutil
from basicclass.getbackcolor import replace_border_color,get_dominant_color, replace_color
from basicclass.newimgcut import get_parts_similar,get_parts
from basicclass.hashdiff import compare_image_with_hash
app = Flask(__name__)
bl_files = [‘logo.jpg‘,‘meixin2.jpg‘]
bl_dirs = []
# 定义路由
@app.route(‘/hello/<name1>/<name2>‘)
def hello(name1, name2):
# # 接收图片
# upload_file = request.files[‘file‘]
# # 获取图片名
# file_name = upload_file.filename
# # 文件保存目录(桌面)
# file_path = r‘images/‘
# if upload_file:
# # 地址拼接
# file_paths = os.path.join(file_path, file_name)
# # 保存接收的图片到桌面
# upload_file.save(file_paths)
# # 随便打开一张其他图片作为结果返回,
# with open(r‘images/yp1.jpg‘, ‘rb‘) as f:
# res = base64.b64encode(f.read())
# return res
# with open("images/original_01.png", "rb") as f:
# # b64encode是编码,b64decode是解码
# base64_data = base64.b64encode(f.read())
# # base64.b64decode(base64data)
# print(base64_data)
# with open("images/original_01.png", "rb") as f:
# # b64encode是编码,b64decode是解码
# base64_data = base64.b64encode(f.read())
# print(base64_data)
# whj = {"name":‘老王‘}
# return render_template(‘static/index.html‘,**whj)
return ‘Hello %s!‘ % name1 + name2
# return "hello"
# ls_f = redi.get(photo)
# ls_f1 = base64.b64decode(ls_f)
# # 将字符流写入BytesIO(主要用于读取缓存中的数据)
# by = BytesIO(ls_f1)
# return send_file(by, mimetype=‘image/png‘)
@app.route(‘/blog/<int:postID>‘)
def show_blog(postID):
return ‘Blog Number %d‘ % postID
@app.route(‘/rev/<float:revNo>‘)
def revision(revNo):
return ‘Revision Number %f‘ % revNo
@app.route(‘/admin‘)
def hello_admin():
# name = request.args[‘name‘]
print(‘1111111111111‘)
# print(name)
return ‘222222‘
@app.route(‘/guest/<guest>‘)
def hello_guest(guest):
return ‘Hello %s as Guest‘ % guest
@app.route(‘/user/<name>‘)
def user(name):
if name == ‘admin‘:
return redirect(url_for(‘hello_admin‘))
else:
return redirect(url_for(‘hello_guest‘, guest=name))
@app.route(‘/popopo/<user>‘)
def hello_name(user):
return render_template(‘hello.html‘, name=user)
@app.route(‘/‘)
def index():
return render_template("index.html")
# return render_template("recog_result.html")
@app.route(‘/success/<name>‘)
def success(name):
return ‘welcome %s‘ % name
@app.route(‘/login‘, methods=[‘POST‘, ‘GET‘])
def login():
if request.method == ‘POST‘:
user = request.form[‘name‘]
return redirect(url_for(‘success‘, name=user))
else:
print("111111111111")
user = request.args.get(‘name‘) + "111111"
return redirect(url_for(‘success‘, name=user))
@app.route(‘/getimg/<filename1>/<filename2>‘)
def get_img(filename1, filename2):
path3 = ‘static/images/‘ + str(random_num()) + ‘.png‘
path4 = ‘static/images/test4.png‘ + str(random_num() + 1) + ‘.png‘
image_diff.get_img_result(
‘static/images/‘ +
filename1,
‘static/images/‘ +
filename2,
path3,
path4)
time.sleep(5)
img_path1 = path3.replace(‘static‘, ‘.‘)
img_path2 = path4.replace(‘static‘, ‘.‘)
# img_stream = return_img_stream(img_path)
return render_template(‘img.html‘, upload_img1=‘./images/‘ + filename1, upload_img2=‘./images/‘ + filename2,
img_path1=img_path1, img_path2=img_path2)
"""
这是一个展示Flask如何读取服务器本地图片, 并返回图片流给前端显示的例子
"""
def return_img_stream(img_local_path):
"""
工具函数:
获取本地图片流
:param img_local_path:文件单张图片的本地绝对路径
:return: 图片流
"""
base64_data = ‘‘
img_stream = ‘‘
with open(img_local_path, ‘rb‘) as img_f:
img_stream = img_f.read()
img_stream = base64.b64encode(img_stream)
return img_stream
@app.route(‘/qingchutp/<destdir>/<yuandir>‘)
def qingchu_imgs(destdir,yuandir):
‘‘‘清楚系统图片缓存
:return:
‘‘‘
rootdir = r"static/images" # 选取删除文件夹的路径,最终结果删除img文件夹
# rootdir = r""+ url_for(‘static‘, filename=‘img2‘) # 选取删除文件夹的路径,最终结果删除img文件夹
filelist = os.listdir(rootdir) # 列出该目录下的所有文件名
for f in filelist:
filepath = os.path.join(rootdir, f) # 将文件名映射成绝对路劲
# if os.path.isfile(filepath): # 判断该文件是否为文件或者文件夹
# print(filepath)
# os.remove(filepath) # 若为文件,则直接删除
# print(str(filepath) + " removed!")
if os.path.isdir(filepath):
print(filepath)
if (destdir not in filepath) and (yuandir not in filepath):
shutil.rmtree(filepath, True) # 若为文件夹,则删除该文件夹及文件夹内所有文件
print("dir " + str(filepath) + " removed!")
return ‘清除成功‘
def qingchu_files(bl_files,bl_dirs):
‘‘‘清楚系统图片缓存
:return:
‘‘‘
rootdir = r"static/images" # 选取删除文件夹的路径,最终结果删除img文件夹
# rootdir = r""+ url_for(‘static‘, filename=‘img2‘) # 选取删除文件夹的路径,最终结果删除img文件夹
filelist = os.listdir(rootdir) # 列出该目录下的所有文件名
for f in filelist:
filepath = os.path.join(rootdir, f) # 将文件名映射成绝对路劲
if os.path.isfile(filepath): # 判断该文件是否为文件或者文件夹
for i in range(len(bl_files)):
if bl_files[i] not in filepath:
filepath = filepath.replace(‘\\‘,‘/‘)
os.remove(filepath) # 若为文件,则直接删除
print(str(filepath) + " removed!")
# print(filepath)
# os.remove(filepath) # 若为文件,则直接删除
# print(str(filepath) + " removed!")
if os.path.isdir(filepath):
print(filepath)
for i in range(len(bl_dirs)):
if bl_dirs[i] not in filepath:
shutil.rmtree(filepath, True) # 若为文件夹,则删除该文件夹及文件夹内所有文件
print("dir " + str(filepath) + " removed!")
# if destdir in filepath or yuandir in filepath:
# return ‘清除成功‘
# 设置允许的文件格式
ALLOWED_EXTENSIONS = set([‘png‘, ‘jpg‘, ‘JPG‘, ‘PNG‘, ‘bmp‘, ‘pdf‘])
def allowed_file(filename):
return ‘.‘ in filename and filename.rsplit(‘.‘, 1)[1] in ALLOWED_EXTENSIONS
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)
# 添加路由
@app.route(‘/upload‘, methods=[‘POST‘, ‘GET‘])
def upload():
if request.method == ‘POST‘:
# 通过file标签获取文件
f1 = request.files[‘file1‘]
f2 = request.files[‘file2‘]
# if not (f1 and allowed_file(f1.filename)):
# return jsonify({"error": 1001, "msg": "图片类型:png、PNG、jpg、JPG、bmp"})
# if not (f2 and allowed_file(f2.filename)):
# return jsonify({"error": 1001, "msg": "图片类型:png、PNG、jpg、JPG、bmp"})
# 当前文件所在路径
basepath = os.path.dirname(__file__)
# 一定要先创建该文件夹,不然会提示没有该路径
# upload_path1 = os.path.join(basepath, ‘static/images‘, secure_filename(f1.filename))
# upload_path2 = os.path.join(basepath, ‘static/images‘, secure_filename(f2.filename))
upload_path1 = os.path.join(
basepath,
‘static/images‘,
secure_filename(
f1.filename))
upload_path2 = os.path.join(
basepath,
‘static/images‘,
secure_filename(
f2.filename))
print(‘filename:‘, f1.filename)
print(‘filename:‘, f2.filename)
filename1 = f1.filename
filename2 = f2.filename
filename3 = str(Util().random_num())+‘.png‘
filename4 = str(Util().random_num()+1) + ‘.png‘
# 保存文件
f1.save(upload_path1)
f2.save(upload_path2)
single_pyMuPDF_fitz(pdfPath=‘static/images/‘ + filename1, imagePath=‘static/images/‘ + filename3)
single_pyMuPDF_fitz(pdfPath=‘static/images/‘ + filename2, imagePath=‘static/images/‘ + filename4)
# 返回上传成功界面
return render_template(‘upload_ok.html‘, filename1=filename1,filename2=filename2, filename3=filename3,filename4=filename4)
# 重新返回上传界面
return render_template(‘upload.html‘)
@app.route(‘/pdftopng/<filename1>/<filename2>‘)
def pdftopng(filename1, filename2):
# pdf图片转为png格式
# pdfPath1 = ‘./../images/saomiaotu.pdf‘
# pdfpath2 = ‘./../images/yuantu.pdf‘
pdfPath1 = ‘static/images/‘ +filename1
pdfpath2 = ‘static/images/‘ +filename2
dest_png_path = ‘static/images/destpng‘ + str(Util().random_num()) # 目标png文件夹名称
yuantuPath = ‘static/images/yuantu‘ + str(Util().random_num())
# auto_cut_png_path = ‘../images/autocutpng‘+str(self.util.random_num()+1)
# #自动切割后的图片文件夹
print(dest_png_path)
print(yuantuPath)
pyMuPDF_fitz(pdfPath1, yuantuPath)
pyMuPDF_fitz(pdfpath2, dest_png_path)
recog_images = []
img_part = 0
# 遍历文件夹下所有文件
work_dir = dest_png_path
for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
for filename in filenames:
file_path = os.path.join(parent, filename)
# print(‘文件名:%s‘ % filename)
# print(‘文件完整路径:%s\n‘ % file_path)
img_path = dest_png_path + ‘/‘ + filename
scann_cut_img_path = dest_png_path + ‘/‘ + ‘cut_‘ + filename
img_cut_white(
img_path,
scann_cut_img_path,
tagrt_rgb_x,
tagrt_rgb_y)
# if not os.path.exists(auto_cut_png_path): # 判断存放图片的文件夹是否存在
# os.makedirs(auto_cut_png_path) # 若图片文件夹不存在就创建
# 如果图片切割完 进行模板匹配
if os.path.exists(scann_cut_img_path):
target_path = yuantuPath + "/images_0.png"
template_path = scann_cut_img_path
# match_path = "static/images/result.png"
template_cut_img_path = dest_png_path + ‘/‘ + ‘template_part_‘ + filename
# 匹配目标图片
x0, y0, x1, y1 = match_target(
target_path, template_path)
# 根据返回的两个像素点切割图片
obj = Util()
obj.cut_img_by_point(
img_path=target_path,
x0=x0,
x1=x1,
y0=y0,
y1=y1,
cut_img_path=template_cut_img_path)
# 将模板匹配到的图片的边框红色去掉
# replace_border_color(template_cut_img_path)
#
# print(scann_cut_img_path,template_cut_img_path)
# 改变图片的背景颜色
target_rgb = get_dominant_color(scann_cut_img_path)
replace_path_scan = scann_cut_img_path.replace(‘.‘,‘_white.‘)
replace_color(scann_cut_img_path, replace_path_scan, target_rgb)
target_rgb = get_dominant_color(template_cut_img_path)
replace_path_yuan = template_cut_img_path.replace(‘.‘, ‘_white.‘)
replace_color(template_cut_img_path,replace_path_yuan,target_rgb)
## 对图片进行等分切割,进行每部分对比
dest_folder_scan = dest_png_path+"/whitescan"+str(Util().random_num())
dest_folder_yuan = dest_png_path + "/whiteyuan" + str(Util().random_num())
dest_scan_points = get_parts(replace_path_scan,64)
get_parts_similar(replace_path_scan, 256, dest_folder=dest_folder_scan)
get_parts_similar(replace_path_yuan, 256, dest_folder=dest_folder_yuan)
# 遍历文件夹下所有文件
work_dir = dest_folder_scan
difflag = []
for parent, dirnames, filenames in os.walk(work_dir, followlinks=True):
for filename in filenames:
file_path_scan = os.path.join(parent, filename)
file_path_yuan = os.path.join(parent.replace(dest_folder_scan,dest_folder_yuan), filename)
# print(‘文件名:%s‘ % filename)
# print(‘文件完整路径:%s\n‘ % file_path_scan)
# print(‘文件完整路径:%s\n‘ % file_path_yuan)
dif = compare_image_with_hash(file_path_scan, file_path_yuan, max_dif=0)
print(dif)
if dif >= 30:
# if dif >= 5 and dif <=15:
print(dif)
index = int(filename.replace(‘image-‘,‘‘).replace(‘.png‘,‘‘))
difflag.append(dest_scan_points[index-1])
print(difflag)
res_scan_path = dest_png_path+‘/‘+‘scan‘+str(Util().random_num())+‘.png‘
res_yuan_path = dest_png_path + ‘/‘ + ‘yuan‘+str(Util().random_num())+‘.png‘
# dif_mark(scann_cut_img_path,template_cut_img_path,res_scan_path,res_yuan_path,difflag)
get_img_result(scann_cut_img_path,template_cut_img_path,res_scan_path,res_yuan_path)
img_part += 1
dit_image = {‘scann‘: res_scan_path.replace(‘static/‘, ‘‘),
‘temp‘: res_yuan_path.replace(‘static/‘, ‘‘), ‘part‘: ‘第‘ + str(img_part) + ‘部分對比圖片‘}
recog_images.append(dit_image)
# result_path = dest_png_path + ‘/result‘ + # str(Util().random_num()) # 目标png文件夹名称
# if not os.path.exists(result_path): # 判断存放图片的文件夹是否存在
# os.makedirs(result_path) # 若图片文件夹不存在就创建
# # 进行图片识别并标识图片差异
# imga_path = scann_cut_img_path
# imgb_path = template_cut_img_path
# print(‘imga_path:‘ +imga_path)
# print(‘imga_path:‘ +imgb_path)
# # scann_path = result_path + ‘/scann‘ + str(Util().random_num() + 1) + ‘.png‘
# # template_path = result_path + ‘/template‘ + str(Util().random_num() + 1) + ‘.png‘
# scann_path = result_path + ‘/scann‘ + # str(Util().random_num() + 1) + ‘.png‘
# template_path = result_path + ‘/template‘ + # str(Util().random_num() + 1) + ‘.png‘
# 识别两张图片并标识差异点
# try:
# dif_two_pic(imga_path, imgb_path, scann_path, template_path)
# img_part += 1
#
# dit_image = {‘scann‘: scann_path.replace(‘static/‘, ‘‘),
# ‘temp‘: template_path.replace(‘static/‘, ‘‘), ‘part‘: ‘第‘ + str(img_part) + ‘部分對比圖片‘}
#
# recog_images.append(dit_image)
# except Exception as e:
# print(e)
# dif_two_pic(imga_path, imgb_path, scann_path, template_path)
#
# img_part += 1
#
# dit_image = {‘scann‘: scann_path.replace(‘static/‘,‘‘), ‘temp‘:template_path.replace(‘static/‘,‘‘), ‘part‘:‘第‘+str(img_part)+‘部分對比圖片‘}
#
# recog_images.append(dit_image)
# 删除多余的图片
bl_dirs = [dest_png_path,yuantuPath,‘destpng7151565‘,‘yuantu7151565‘]
# qingchu_files(bl_files,bl_dirs)
if os.path.exists(dest_png_path) and os.path.exists(yuantuPath): # 判断存放图片的文件夹是否存在
# os.makedirs(result_path) # 若图片文件夹不存在就创建
print(‘dest_png_path:‘+dest_png_path)
print(‘yuantuPath:‘ + yuantuPath)
qingchu_imgs(dest_png_path.replace(‘static/images/‘,‘‘), yuantuPath.replace(‘static/images/‘,‘‘))
return render_template("recog_result.html", recog_images=recog_images)
if __name__ == ‘__main__‘:
# app.run(host=host_ip, port=port, debug=True)
app.run(host=‘127.0.0.1‘, port=5000, debug=True)
写这个功能的代码是费了很大劲的,路过的朋友点个赞哈。
交流:3459067873
python智能图片识别系统(图片切割、图片识别、区别标识)
标签:border 服务 write redirect similar append _for 图像 log
原文地址:https://www.cnblogs.com/hongming-blogs/p/13499012.html