批量圖片進行裂紋檢測代碼展示
最近在研究CV,找到一個開源代碼,但是是一張一張圖片處理的,在網上找了批量處理的代碼,但是碰到了各種問題死活運行不了,最后借助chatGPT幫忙寫了一個總算是能運行了,(ㄒoㄒ)。
但是最后展示結果的的窗口又出現了問題,只能手動關閉,輸入plt.close()也沒有反應。遂繼續(xù)求助chatGPT但是給出的結果仍無濟于事,最后發(fā)現在繪圖前加入代碼:plt.ion(),然后plt.close()就能成功運行了o(* ̄▽ ̄*)ブ。
最終,一個能夠進行批量處理圖片,并且每個窗口都能進行1s展示的代碼就出爐了,并且把繪制結果都保存了下來。
代碼如下(需要裝幾個必要的庫:cv,os,numpy等):
# importing necessary libraries
import numpy as np
import CV2
from matplotlib import pyplot as plt
from PIL import Image
import os
import ?time
#保存灰度圖用
counter=1
# 指定保存圖像的文件夾路徑
save_folder = 'D:/pythonuse/crack-detection-opencv-master/huidutu-set'
# 文件夾路徑
folder_path = 'D:/pythonuse/crack-detection-opencv-master/Input-Set'
# 輸出文件夾路徑
output_folder_path = 'D:/pythonuse/crack-detection-opencv-master/Output-Set'
# 創(chuàng)建輸出文件夾
os.makedirs(output_folder_path, exist_ok=True)
# 讀取文件夾中的所有文件
file_list = os.listdir(folder_path)
# 遍歷文件夾中的文件
for file_name in file_list:
? ?# 構建文件的完整路徑
? ?file_path = os.path.join(folder_path, file_name)
? ?# 檢查文件路徑是否為文件
? ?if os.path.isfile(file_path):
? ? ? ?# 使用OpenCV讀取圖像
? ? ? ?img = CV2.imread(file_path)
? ? ? ?# 將圖像轉換為灰度圖像
? ? ? ?gray = CV2.cvtColor(img, CV2.COLOR_BGR2GRAY)
? ? ? ?# 構建輸出文件的完整路徑
? ? ? ?output_file_path = os.path.join(output_folder_path, file_name)
# Image processing ( smoothing )
# Averaging
? ? ? ?blur = CV2.blur(gray,(3,3))
# Apply logarithmic transform
? ? ? ?img_log = (np.log(blur+1)/(np.log(1+np.max(blur))))*255
# Specify the data type
? ? ? ?img_log = np.array(img_log,dtype=np.uint8)
# Image smoothing: bilateral filter
? ? ? ?bilateral = CV2.bilateralFilter(img_log, 5, 75, 75)
# Canny Edge Detection
? ? ? ?edges = CV2.Canny(bilateral,100,200)
# Morphological Closing Operator
? ? ? ?kernel = np.ones((5,5),np.uint8)
? ? ? ?closing = CV2.morphologyEx(edges, CV2.MORPH_CLOSE, kernel)
# Create feature detecting method
# sift = CV2.xfeatures2d.SIFT_create()
# surf = CV2.xfeatures2d.SURF_create()
? ? ? ?orb = CV2.ORB_create(nfeatures=1500)
# Make featured Image
? ? ? ?keypoints, descriptors = orb.detectAndCompute(closing, None)
? ? ? ?featuredImg = CV2.drawKeypoints(closing, keypoints, None)
# Create an output image
? ? ? ?CV2.imwrite(output_file_path, gray)
? ? ? ?plt.ion()
? ? ? ?# 顯示圖像
? ? ? ?plt.subplot(121)
? ? ? ?plt.imshow(img)
? ? ? ?plt.title('Original')
? ? ? ?plt.xticks([])
? ? ? ?plt.yticks([])
? ? ? ?plt.subplot(122)
? ? ? ?plt.imshow(featuredImg, cmap='gray')
? ? ? ?plt.title('Output Image')
? ? ? ?plt.xticks([])
? ? ? ?plt.yticks([])
? ? ? ?# 生成保存圖像的完整路徑
? ? ? ?save_path = os.path.join(save_folder, 'result_' + str(counter) + '.png')
? ? ? ?# 保存圖像
? ? ? ?plt.savefig(save_path)
? ? ? ?counter += 1
? ? ? ?plt.show()
? ? ? ?plt.pause(1) ?# 延時1秒后再關閉
? ? ? ?plt.close()