如何在Python中迭代excel电子表格行?

2024-06-16 08:57:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个脚本,它根据图像的x/y/r像素坐标在图像的特征周围绘制矩形,这一切都运行良好。运行代码如下:

ss = pd.read_excel(xeno_data)

fandc = []
for index, row in ss.head().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})

#Draw a transparent rectangle:
im = im.convert('RGBA')
overlay = Image.new('RGBA', im.size)
draw = ImageDraw.Draw(overlay)

#The x,y,r coordinates are centre of sponge (x,y) and radius (r).
draw.rectangle(((float(fandc[0]['x'])-float(fandc[0]['r']), float(fandc[0]['y'])-float(fandc[0]['r'])), (float(fandc[0]['x'])+float(fandc[0]['r']), float(fandc[0]['y'])+float(fandc[0]['r']))), fill=(255,0,0,55))

img = Image.alpha_composite(im, overlay)
img = img.convert("RGB")
# Remove alpha for saving in jpg format.

img.show()

此代码生成所需的结果,您可以从this image中看到,它已成功地在图像中心底部的特征上绘制了一个褪色的红色矩形

但是,这是针对数据的第一行(“fandc[0]”)定制的。如何调整此代码以自动迭代或循环我的电子表格(xeno_数据)的每一行,即“fandc1”、“fandc[2]”、“fandc[3]”等

谢谢大家


Tags: 代码图像img绘制特征coordsfloatfilename
1条回答
网友
1楼 · 发布于 2024-06-16 08:57:23

在无法访问相同数据的情况下,您最初基于fandc[0]进行绘图,并希望遍历所有其他矩形fandc[1],fandc[2],等等。然后您可以尝试:

    for i in range(len(fandc)):
        draw.rectangle(((float(fandc[i]['x'])-float(fandc[i]['r']), float(fandc[i]['y'])-float(fandc[i]['r'])), (float(fandc[i]['x'])+float(fandc[i]['r']), float(fandc[i]['y'])+float(fandc[i]['r']))), fill=(255,0,0,55))

看看我们如何用迭代索引i替换初始索引0

如果您正在努力让循环正常工作,那么最好在网上做一个关于循环的教程,并用更简单的代码来练习循环。有关详细信息,请参见https://www.w3schools.com/python/python_for_loops.asp

相关问题 更多 >