【发布时间】:2019-04-30 21:07:23
【问题描述】:
我正在解决我需要解决的问题之一:
- 从文件夹中读取所有图像,该文件夹接受除 PDF 之外的所有图像格式。
- 查找轮廓并将所有轮廓图像写入指定的输出文件夹。
- 在文件名下创建子文件夹,并将分割后的图片写入相关文件夹。
我已经在 python 中完成了它的程序,但是现在我在为每个问题点编写函数并使用命令行执行程序时遇到了麻烦。
基本上我必须编写通用代码,以便将来如果我获得新图像,我不需要更改代码(这意味着它应该在 python 文件内的命令控制台上要求输入文件,会有通用代码是适用于任何文件)。
import cv2
import numpy as np
import os
os.getcwd()
os.chdir("C:/Users/ani/Downloads/Assignment")
# variable
filename = "1 (103)_A_0_0_NAME"
# create a folder for this image
path = "C:/Users/ani/Desktop//"+filename
if not os.path.exists(path):
os.makedirs(path)
# load image in grayscale
img = cv2.imread(filename+".jpg",0)
# threshold image
ret,mask = cv2.threshold(img,240,255,cv2.THRESH_BINARY_INV)
# find contours
contours, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# sort contours
sorted_ctrs = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0])
for i in range(len(sorted_ctrs)):
# get contour
cnt = sorted_ctrs[i]
# get the dimensions of the boundingRect
x,y,w,h = cv2.boundingRect(cnt)
# create a subimage based on boundingRect
sub_img = img[y:y+h,x:x+w]
sub_img = ~sub_img
# save image of contour with indexed name
cv2.imwrite(path +"\contour_"+str(i)+".jpg", sub_img)
我想要一个通用代码,它在命令提示符下输入图像文件,这基本上意味着一个 python 函数代码文件,它执行所有 3 个步骤而不在程序文件中指定输入文件位置。 (附输入文件)
第一个:
第二个:
第三:
【问题讨论】:
标签: python function opencv image-processing