Apr-11-2020, 09:43 AM
Hi all,
I have a script used to draw rectangles over multiple features within an image, based upon the pre-extracted x/y/r pixel coordinates of said features. This script is as follows:
For each one I need it to:
If any clarification is needed ask away!
Thanks, Rhod
I have a script used to draw rectangles over multiple features within an image, based upon the pre-extracted x/y/r pixel coordinates of said features. This script is as follows:
import os import numpy as np import pandas as pd import PIL from PIL import Image from PIL import ImageDraw import glob import re # import RegEx module xeno_data = 'C:\file_path\data.xlsx' ss = pd.read_excel(xeno_data)These three pixel coord values (x/y/r) are all contained within the same column in the Excel spreadsheet, hence the following step to seperate them into seperate numbers:
# Extract filenames and coordinates from Excel spreadsheet (data.xlsx): FandC = [] for index, row in ss.iterrows(): filename = row['filename'] coords = row['xyr_coords'] # Use RegEx to find anything that looks like a group of digits, possibly seperated by decimal point: x, y, r = re.findall(r'[0-9.]+',coords) print(f'DEBUG: filename={filename}, x={x}, y={y}, r={r}') FandC.append({'filename': filename, 'x':x, 'y':y, 'r':r})Creating new dataframes for the values of interest - 'filename', 'x', 'y', and 'r':
fandc=pd.DataFrame(FandC) #creates a dataframe for "filename", "x", "y", and "r". fandc['filename'] [fandc['filename']=='Image1.jpg'] # shows "fandc['filename']" where the "filename" is equal to (==) the string "Image1.jpg". fandc_f = fandc[fandc['filename']=='Image1.jpg'] # create new df called "fandc_f" that only includes "fandc['filename']" where "filename" == "Image1.jpg". for index , row in fandc_f.iterrows(): row breakDraw a transparent rectangle:
im = im.convert('RGBA') overlay = Image.new('RGBA', im.size) draw = ImageDraw.Draw(overlay) for index, row in fandc_f.iterrows(): for i in range(len(fandc_f)): draw.rectangle(((float(row['x'])-float(row['r']), float(row['y'])-float(row['r'])), (float(row['x'])+float(row['r']), float(row['y'])+float(row['r']))), fill=(255,0,0,55)) # Remove alpha for saving in jpg format: img = Image.alpha_composite(im, overlay) img = img.convert("RGB")This code is working perfectly... for one image. However, now I need to wrap the whole process in with a big loop on the outside that automatically goes through each unique filenames in a pandas df.
For each one I need it to:
- load the image,
- filter the df for respective filenames,
- apply my rectangle drawing loop,
- save the image,
- and then loop on to next image automatically (as I have thousands of images to process, and cannot do it manually).
If any clarification is needed ask away!

Thanks, Rhod