我正在解决我需要解决的问题之一:
我已经用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个步骤,而无需在程序文件中指定输入文件的位置。(附加输入文件)
第一:
第二名:
第三名:
似乎您想了解“如何读取/处理命令行参数? ”。请参阅链接以获取更详细的答案,但简而言之-用于sys.argv
访问以下内容:
import sys
print(sys.argv[1:])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句