欢迎光临散文网 会员登陆 & 注册

批量图片进行裂纹检测代码展示

2023-05-30 23:07 作者:阴阳光子  | 我要投稿

最近在研究CV,找到一个开源代码,但是是一张一张图片处理的,在网上找了批量处理的代码,但是碰到了各种问题死活运行不了,最后借助chatGPT帮忙写了一个总算是能运行了,(ㄒoㄒ)。

但是最后展示结果的的窗口又出现了问题,只能手动关闭,输入plt.close()也没有反应。遂继续求助chatGPT但是给出的结果仍无济于事,最后发现在绘图前加入代码: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'

# 创建输出文件夹
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()

批量图片进行裂纹检测代码展示的评论 (共 条)

分享到微博请遵守国家法律