Python snippets

Jan. 3, 2021

Python snippets that are too long for me to remember.

These scripts are classified into different usage scenario. Some of them are easier to understand while not so efficient.

Read all certain type of files from a directory


images = [os.path.join(dir, name) for name in os.listdir(dir) if
			os.path.isfile(os.path.join(dir, name)) & name.endswith('.jpg')]

Taking argument from command line


#argsparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-x', '--xml', help='blast xml input', nargs='+')
parser.add_argument('-a', '--aminoacid', help='genome_aa_file_name', nargs='+')

args = parser.parse_args()
xml_files=args.xml
genome_aa_file_name = args.aminoacid

Image processing

from PIL import ImageEnhance, Image
resize_factor = 0.1
image = Image.open(image_path)
width, height = image.size
print(image.size)
height = int(height*resize_factor)
width = int(width*resize_factor)
image = image.resize((width, height))

# rotate image
if width > height:
angle = 270
print("rotate")
image = image.rotate(angle, expand=True)
width, height = image.size
print(image.size)
# enhancement
image = ImageEnhance.Contrast(image).enhance(0.6)
image = ImageEnhance.Brightness(image).enhance(1.7)
# image.show()
# pixel manipulation
image_data = image.load()
for loop1 in range(width):
    for loop2 in range(height):
        r,g,b = image_data[loop1,loop2]
        # print(r)
        if b>g or b>r:
            image_data[loop1,loop2] = 0,0,0
        elif r-b>200:
            image_data[loop1,loop2] = 0,0,0
new_file_name = file_name.loc[image_name].genotype + '_' + image_name
new_file_name = new_file_name.replace(' ','_')
new_file_name = new_file_name.replace('JPG','jpg')
new_file_name = shelter_num + new_file_name
image.save(new_file_name)	

Compose image sequences into video

import cv2
img_array = []
ww = 640
hh = 480
color = (0,0,0)

for img_path in img_path_list:	
	img = cv2.imread(img_path)
	height, width, layers = img.shape
	x = int((ww-width)/2)
	y = int((hh-height)/2)
	result = np.full((hh,ww,layers), color, dtype=np.uint8)
	result[y:y+height, x:x+width] = img
	img_array.append(result)

# write a video composed of images
size = (ww,hh)
#fourcc mp4v or avc1 for mac, windows and linux need different fourcc
video = cv2.VideoWriter('dirt_image_sequence.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 6, size)
 
for i in range(len(img_array)):
    video.write(img_array[i])
video.release()