Python Cheat Sheet

Frequenly needed bits of python code

Page content

Sometimes need this but can’t find rightaway. So keeping them all here.

They are not something new, just a bunch of copy-pastes, but they work for me, and I hope you might find them useful too.

Awesome Python in 3d

Common Anaconda commands

Check if Conda is installed

conda -V

Check if Conda is up to date

conda update conda

Create a virtual environment

conda create -n newenvname python=3.12 anaconda

Activate your virtual environment

source activate newenvname

Install additional Python packages to a virtual environment

conda install -n newenvname [package]

Deactivate your virtual environment

source deactivate

Delete the virtual environment

conda remove -n newenvname --all

Draw rectangle

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), color=(255,0,0), thickness=2)

x1,y1 ------
|          |
|          |
|          |
--------x2,y2

to append the follow-up questions below:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

I have a PIL Image object and I want to draw rectangle on this image. I want to use opencv2 and draw rectangle, and then convert back to PIL Image object. Here is how I do it:

# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)

Easy argument parsing

import json

#---------------------------------------------------------------------------
def do_some_awesomeness(src_file, tgt_file):
    print('Converting some stuff from {} to {}'.format(src_file, tgt_file))

#---------------------------------------------------------------------------
def run():
    import argparse

    parser = argparse.ArgumentParser(description="Some mega useful and efficient python tool.")
    parser.add_argument("-s", "--src", dest="src_file",
        help="input json filename")
    parser.add_argument("-t", "--tgt", dest="tgt_file",
        help="output json filename")
    
    args = parser.parse_args()

    do_some_awesomeness(args.src_file, args.tgt_file)

if __name__ == '__main__':
    run()

Then call it like

python ave_roma.py --src 1.json --tgt 2.json

Load and save json

import json

def do_convert(src_file, tgt_file):

    with open(src_file) as f:
        src = json.load(f)

    tgt = src # :)

    with open(tgt_file, 'w', encoding='utf-8') as f:
        json.dump(tgt, f, ensure_ascii=False, indent=4)

Get filename without extention

import os

print(os.path.splitext("/path/to/some/file.txt")[0])

will print:

/path/to/some/file