Monday, August 22, 2022

Read point click coordinates on image in pixel and inches

 Listed below is a python code that uses opencv library to read an image and read the coordinate at mouse click. Left mouse click will display the coordinates in both pixels and inches while right mouse click will clear the coordinates by reloading the image.


# importing the module
import cv2


# Get list of all events in cv2... the one we want to use is the 'EVENT_LBUTTONDOWN' (left click)
all_events = [i for i in dir(cv2) if 'EVENT' in i]
# print(all_events)
# print(dir(cv2.EVENT_LBUTTONDBLCLK))


# reading the image
img_file = r"IMG_20180426_235051_042.jpg"
img = cv2.imread(img_file, 1)

# displaying the image
cv2.imshow('Title image window...', img)


# --------------------------------------------------------
# define the callback function...
def click_event(event, x, y, flags, params):
	global img
	
	if event == cv2.EVENT_LBUTTONDOWN:
		print(x, '---', y)

		# convert pixels to inches
		# Assuming PixelsPerInch resolution (PPI) is 96, therefore: PPI = 96 px / inch
		# 1 pixel = 1 inch / 96 >>>> 1 pixel = 0.010417 inch
		x_inch = round(x * 0.010417, 2)
		y_inch = round(y * 0.010417, 2)

		font = cv2.FONT_HERSHEY_SIMPLEX
		cv2.putText(img, f'{str(x)}, {str(y)}px ({x_inch}, {y_inch}inches)', (x, y), font, 1, (255, 0, 0), 2)
		cv2.imshow('Title image window...', img)


	# Clear screen text by right click...
	if event == cv2.EVENT_RBUTTONDOWN:
		print('Right Click...')

		img = cv2.imread(img_file, 1)
		cv2.imshow('Title image window...', img)
		cv2.setMouseCallback('Title image window...', click_event)



# use the callback function by setting the Mouse callback....
cv2.setMouseCallback('Title image window...', click_event)
# --------------------------------------------------------


# wait for a key to be pressed to exit
cv2.waitKey(0)

# close the window
cv2.destroyAllWindows()



That is it!

Friday, August 19, 2022

Copy a file to multiple directories

 Lets say we got nested folders as seen below where we want copy a file (text file in this case) into all the folders.


The python script below does what was stated above.


import os
import glob
import shutil
txt_file = r"C:\Users\Yusuf_08039508010\Documents\...\PDF Others\textfile.txt"
fldr = r'C:\Users\Yusuf_08039508010\Documents\Jupyter_Notebook\2022\...\PDF Others'

# Change dir to parent directory and get all subfolder...
os.chdir(fldr)
list_of_folder = glob.glob('**/', recursive=True)

# Copy text file from source (src) to destination (dst)
for f in list_of_folder:
    print('Processing...', f)
    shutil.copy( txt_file, f ) # shutil.copy( src, dst )


Enjoy!