<jupyter_start><jupyter_text>I want to take a Python script, orginally created to run on the commandline, and put in Jupyter.How do you pass this script arguments?The example below show you how.<jupyter_code>#!/usr/bin/python3
'''
DESCRIPTION
    This script counts shapes within an input image, outlines the shapes with a red line,
    annotates the image with the number of shapes found, and then writes the image to disk.

USAGE
    python shape_counter.py -i random-shapes.png -o output.png
'''


# import the necessary packages
import sys
import cv2
import imutils
import argparse


# create the command line since your within Jupyter
sys.argv = ["./shape_counter.py",
            "-i", "/home/jeff/src/Jupyter-Notebooks/DataSets/Images/random-shapes-1.png",
            "-o", "/home/jeff/tmp/output.png"]


def count_shapes(image):
    # convert the image to grayscale, blur it, and threshold it
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

    # extract contours from the image
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]

    # loop over the contours and draw them on the input image
    for c in cnts:
        cv2.drawContours(image, [c], -1, (0, 0, 255), 2)

    # display the total number of shapes on the image
    text = "Total number of shapes = {}".format(len(cnts))
    cv2.putText(image, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
                0.5, (0, 0, 255), 2)

    return len(cnts), image


def LineArgumentParser():
    # construct the argument parser and parse the arguments
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("-i", "--input", required=True,
                    help="name of input image file")
    ap.add_argument("-o", "--output", required=True,
                    help="name of output image file")
    ap.add_argument("-I", "--input_path", required=False,
                    default="",
                    help="path to input image")
    ap.add_argument("-O", "--output_path", required=False,
                    default="",
                    help="path to output image")
    return vars(ap.parse_args())


if __name__ == "__main__":
    # parse the line arguments
    args = LineArgumentParser()

    # load the input image from disk
    in_image = cv2.imread(args["input_path"] + args["input"])

    # pass the image to the shape counter
    count, out_image = count_shapes(in_image)

    print("Total number of shapes = ", count)

    # write the output image to disk
    cv2.imwrite(args["output_path"] + args["output"], out_image)<jupyter_output>Total number of shapes =  17<jupyter_text>parsing tuple with strings<jupyter_code>import argparse

parser= argparse.ArgumentParser()
parser.add_argument ('-f', '--file', nargs=3, action='append')

cmline = '-f file1 string1 string2 -f file2 string3 string4 -f file3 string5 string6'
args = parser.parse_args(cmline.split())
out = parser.parse_args(cmline.split()).file

print(args, '\n')
print(out, '\n')

for f in out:
    print(tuple(f))<jupyter_output>Namespace(file=[['file1', 'string1', 'string2'], ['file2', 'string3', 'string4'], ['file3', 'string5', 'string6']]) 

[['file1', 'string1', 'string2'], ['file2', 'string3', 'string4'], ['file3', 'string5', 'string6']] 

('file1', 'string1', 'string2')
('file2', 'string3', 'string4')
('file3', 'string5', 'string6')<jupyter_text>parsing tuple with integers<jupyter_code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument ('-r', '--resolution', nargs=2, type=int, action='append')

cmline = '-r 300 500'
args = parser.parse_args(cmline.split())

print(args, '\n')

for r in args:
    print(tuple(r))<jupyter_output>Namespace(resolution=[[300, 500]])<jupyter_text>define your own typesee https://stackoverflow.com/questions/9978880/python-argument-parser-list-of-list-or-tuple-of-tuples<jupyter_code>import argparse

def coords(s):
    try:
        x, y, z = map(int, s.split(','))
        return x, y, z
    except:
        raise argparse.ArgumentTypeError("Coordinates must be x,y,z")

        
parser= argparse.ArgumentParser()
parser.add_argument('--cord', help="Coordinate", dest="cord", type=coords, nargs=3)

cmline = 'program -r 300,500,700'
args = parser.parse_args(cmline.split())

print(args, '\n')
x = 100
y = 200
print(tuple([x, y]))
x = [1, 2, 3, 4]
print(x[1])<jupyter_output>2
{'fraction_non_alphanumeric': 0.14288864388092612, 'fraction_numerical': 0.02844542447629548, 'mean_word_length': 3.6004056795131847, 'pattern_counts': {'":': 1, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '543945', 'license': 'Unlicense', 'n_tokens_mistral': 1600, 'n_tokens_neox': 1517, 'n_words': 415, 'path': 'notebooks/Using Jupyter/Jupyter, Python, argparse, and Command Line Arguments.ipynb', 'repo_name': 'jeffskinnerbox/computer-vision', 'size': '4535'}