1 回答
TA贡献1836条经验 获得超13个赞
如您所问,以下代码将“以文件名的名称创建子文件夹并将分段图像写入相关文件夹”。
import cv2
import numpy as np
import glob,os,sys
class Imageprocessing:
def readImages(inputFolder):
ext = ['.png', '.jpg', '.gif', '.jpeg', '.tif', '.tiff']
files = []
path = inputFolder + "/*.*"
files = glob.glob(path)
imageFiles=[]
for i in files:
exten=os.path.splitext(i)[1]
if exten in ext:
imageFiles.append(i)
return imageFiles
def processImage(imageFiles):
for imagePath in imageFiles:
img_name = os.path.splitext(os.path.basename(imagePath))[0]
new_folder = sys.argv[2]+'/'+img_name+'/'
os.makedirs(new_folder, exist_ok=True)
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
kernel = np.ones((10, 0), np.uint8)
dilated_img = cv2.dilate(thresh, kernel, iterations=0)
img, contours, hierarchy = cv2.findContours(dilated_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_ctrs = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0])
for i, ctr in enumerate(sorted_ctrs):
x, y, w, h = cv2.boundingRect(ctr)
cv2.drawContours(image, [ctr], -1, (0, 0, 255), 3)
roi = image[y:y + h, x:x + w]
if w > 3 and h > 10:
cv2.imwrite(new_folder+'{}.png'.format(i), roi)
cv2.imshow('contours', image)
cv2.waitKey(0)
imageFiles = Imageprocessing.readImages(sys.argv[1])
Imageprocessing.processImage(imageFiles)
# press 'esc' to close the image window
# execute as : python file.py path\to\input path\to\output
# each argument seperated by space
这将为每个文件名在指定sys.argv[2]为分割图像的位置创建一个文件夹,并绘制轮廓。
您可以调整 'w' 和 'h'if w > 3 and h > 10:
或内核或 'cv2.dilate' 中的迭代值,以将此代码调整为图像文件中不同大小的字符。(目前代码已调整为您提供的图片链接)
添加回答
举报