python智慧圖片識別系統(圖片切割、圖片識別、區別標識)
阿新 • • 發佈:2020-08-13
@目錄
技術介紹
你好! 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