Python Forum

Full Version: Return draw.rectangle pixel coordinate data to .csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm a marine science student using machine learning to automate seafloor monitoring and imagery analysis.

I already have an extensive script that's functioning well. The purpose of the script is to itterate through images and draw rectangles around a specific species within the imagery, based upon previously manually extracted pixel coordinate data in Excel spreadsheet format:

FandC = []
    for index, row in ss.iterrows():
        filename = row['filename']
        coords   = row['xyr_coords']
        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})

master_df = pd.DataFrame(FandC)
master_df.sort_values('filename', inplace = True, axis = 0)
img1_df = master_df[master_df['filename']=='image1.jpg']

def draw_rectangle(filename, master_df):
    img_path = 'C:\\filepath\\{}'.format(filename)
    im= Image.open(img_path)
    img1_df = master_df[master_df['filename'].str.match(filename)]
    im = im.convert('RGBA')
    overlay = Image.new('RGBA', im.size)
    draw = ImageDraw.Draw(overlay)

    for index, row in img1_df.iterrows():
        for i in range(len(img1_df)):
            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))
            #return im.

    img = Image.alpha_composite(im, overlay)
    img = img.convert("RGB")
    img.save('C:\\filepath\\rect_{}'.format(filename))

for i, row in master_df.iterrows():
    if i == 0:
        filename_tmp = row['filename']
        draw_rectangle(filename_tmp, master_df)
    if row['filename'] == filename_tmp:
        pass
    else:
        filename_tmp = row['filename']
        draw_rectangle(filename_tmp, master_df)    
    if i == 100:      
        break
This all works as intended, and draws rectangles around multiple features within each image and exports the new annotated images to a new folder. Now however, I wish to return/extract the pixel coordinate values of each of the four corners of each rectangle drawn (as calculated in the 'draw.rectangle' line), as a function that can be intergrated into my original script. I would preferably like this in .csv format, with 5 columns aranged as (or something similar to):
'filename', top left (x/y), bottom left (x/y), top right (x/y), bottom right (x/y).

I have been fiddling with this for days and can't seem to execute what I want to achieve, so if someone could point me in the right direction that would be fantasic!

Hope this is clear. Thanks, R