首页 > 解决方案 > 需要帮助围绕现有脚本创建复杂循环

问题描述

我有一个脚本,用于根据所述特征的预提取 x/y/r 像素坐标在图像中的多个特征上绘制矩形。该脚本如下:

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)

这三个像素坐标值 (x/y/r) 都包含在 Excel 电子表格的同一列中,因此以下步骤将它们分成单独的数字:

    # 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})

为感兴趣的值创建新的数据框 - 'filename'、'x'、'y' 和 '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
    break

绘制一个透明矩形:

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")

此代码运行良好......对于一张图片:

IMAGE_OUTPUT

但是,现在我需要在外部使用一个大循环来包装整个过程,该循环会自动遍历 pandas df 中的每个唯一文件名。

对于每一个我需要它:加载图像,过滤相应文件名的df,应用我的矩形绘图循环,保存图像,然后自动循环到下一个图像(因为我有成千上万的图像要处理,但不能这样做手动)。

如果需要任何澄清,请询问!:)

谢谢,罗德

标签: pythonpandasimageloopsimage-processing

解决方案


推荐阅读