如何在Python 2.7中给图像添加圆形?

0 投票
3 回答
3579 浏览
提问于 2025-04-19 03:49

我在使用Python 2.7写代码:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

image_file='test.fits'
hdu_list = fits.open(image_file)
image_data = hdu_list[0].data

plt.imshow(image_data,cmap='gray')
plt.show()

我打开了一个FITS文件,并把里面的数据保存到了一个数组里。

到这里为止没有任何问题。

现在我有两个问题。

第一个问题是: 我想在图像的特定位置添加一个圆圈(或者写一些文字)。我的数据是一个2048 x 2048的浮点值数组。

第二个问题是: 假设我在绘制/添加任何东西之前,把这个图像保存为“test.png”。 在保存为png图像后,我现在想在这个png图像的特定位置添加一个圆圈(或者写一些文字)。我该怎么做呢?

任何帮助都将不胜感激。 谢谢。

3 个回答

1

我之前也遇到过类似的问题,参考了早些时候回答的Jerome Pitogo de Leon的建议。在我的案例中,我有一张bmp格式的图片,我把它保存到了一个叫做'img'的变量里:

import matplotlib.pyplot as plt img = mpimg.imread('img_name.bmp') plt.show()

接着,我查看了一下坐标轴的样子,然后根据我通过观察确定的坐标来指定我的圆圈。

# Define circles
c1 = plt.Circle((100, 600), 50, color=(0, 0, 1))
c2 = plt.Circle((300, 400), 50, color=(1, 0, 0))
c3 = plt.Circle((500, 200), 50, color=(0, 1, 0))

# Open new figure
fig = plt.figure()

# In figure, Image as background
plt.imshow(img)

# Add the circles to figure as subplots
fig.add_subplot(111).add_artist(c1)
fig.add_subplot(111).add_artist(c2)
fig.add_subplot(111).add_artist(c3)

plt.show()
1

你可以试试下面的代码:

hmask,wmask= 0.3,0.3 #radius = 15 pix = 20 AU
m=Ellipse(xy=(0,0),height=hmask,width=wmask)
figure(1).add_subplot(111).add_artist(m)
m.set_color('k')
1

如果你有圆的位置是用像素坐标表示的,可以使用matplotlib里的scatter函数或者Circle类来绘图。
(在这种情况下,绘图的问题其实和astropy没有关系,你应该把它标记为matplotlib。)

如果你有圆的位置是用世界坐标表示的(也就是天空上的经度和纬度),你可以使用aplpy或者wcsaxes来处理。

关于你的第二个问题:你可以用matplotlib或者scikit-image把png图片加载到numpy数组中,然后再用matplotlib来画圆(不过要注意,坐标轴的坐标会不一样……如果可以的话,尽量避免这种情况,或者给出一些代码示例,说明你到底想做什么)。

撰写回答