1

I was solving one of the problem where i need to:

  • Read all the images from folder, which accept all image formats other than PDF.
  • Find contours and write all contour images in to specified the output folder.
  • Create sub folder under the name of filename and write the segmented images to the relevant folders.

I've done program for it in python but now i am having trouble while writing functions for each of the problem point and execute the program using command line.

Basically I have to write general code so that in future if I get new images I don't need to change the code (which means it should ask for input files on command console inside python file there will be general code which is applicable for any file).

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)

I want a general code which take input for image file on command prompt which basically means a python function code file which executes all 3 steps without specifying the input file location in program file. (Input file attached)

1st:

enter image description here

2nd:

enter image description here

3rd:

enter image description here

James Z
  • 12,209
  • 10
  • 24
  • 44
Aks
  • 33
  • 1
  • 8

1 Answers1

0

It seems like you want to know "How to read/process command line arguments?". See link for more elaborated answer, but in short - use sys.argv to access those:

import sys
print(sys.argv[1:])
Eran W
  • 1,696
  • 15
  • 20
  • well i want to know how to write generic program for above problem so that in future if i get new images i don't have to make any changes in the code and one more thing that there need to be no path specified in program. one should specify path on command line that where is images in the system and execute program from there only. – Aks Apr 16 '19 at 05:59
  • Then you should use `sys.argv` to replace the hard-coded `filename` with what the user enters in the command line, then use `os.path` to get the path+filename+extension. – Eran W Apr 18 '19 at 13:55