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:
2nd:
3rd: