【问题标题】:Writing functions and run program on command line在命令行上编写函数和运行程序
【发布时间】: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


    【解决方案1】:

    您似乎想知道“How to read/process command line arguments?”。请参阅链接以获得更详细的答案,但简而言之 - 使用 sys.argv 访问这些:

    import sys
    print(sys.argv[1:])
    

    【讨论】:

    • 好吧,我想知道如何为上述问题编写通用程序,这样以后如果我得到新图像,我就不必对代码进行任何更改,还需要做一件事程序中没有指定路径。应该在命令行上指定系统中图像所在的路径并仅从那里执行程序。
    • 那么你应该使用sys.argv将硬编码的filename替换为用户在命令行中输入的内容,然后使用os.path获取路径+文件名+扩展名。跨度>
    猜你喜欢
    • 2015-06-22
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 2013-03-02
    • 1970-01-01
    相关资源
    最近更新 更多