python - 需要帮助围绕现有脚本创建复杂循环
问题描述
我有一个脚本,用于根据所述特征的预提取 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")
此代码运行良好......对于一张图片:
但是,现在我需要在外部使用一个大循环来包装整个过程,该循环会自动遍历 pandas df 中的每个唯一文件名。
对于每一个我需要它:加载图像,过滤相应文件名的df,应用我的矩形绘图循环,保存图像,然后自动循环到下一个图像(因为我有成千上万的图像要处理,但不能这样做手动)。
如果需要任何澄清,请询问!:)
谢谢,罗德
解决方案
推荐阅读
- java - Kafka 消息过滤
- c# - 如何设置 IHttpClientAdapter.GetAsync 以返回具有 IsSuccessStatusCode 特定值的 HttpResponseMessage?
- python - 如何设置我的 if 语句变量与我的函数相同
- python-3.x - Sklearn 内核密度数据类型
- java - 用单个空格替换所有 2 个或更多空格序列的 Java 字符串方法
- angular - 前段时间在 ionic V4 中使用 Angular 管道
- sql - 将排序表分组为计数、总和、平均值的 5% 段
- java - Docusign 嵌入式编辑
- python - 我正在使用 while 语句构建一个函数,并且只要 while 语句结束,它就什么也不做,尽管有更多的代码
- pysnmp - 将模块限定的 OID 转换为 ObjectIdentity