Skip to main content
 首页 » 编程设计

python之屏蔽位于两条曲线之间的图像 (np.ndarray) 部分

2025年05月04日9dyllove98

从 astropy 借用这个例子:

import numpy as np 
from matplotlib import pyplot as plt 
from astropy.io import fits 
from astropy.wcs import WCS 
from astropy.utils.data import download_file 
 
fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' 
image_file = download_file(fits_file, cache=True) 
hdu = fits.open(image_file)[0] 
wcs = WCS(hdu.header) 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
plt.imshow(hdu.data, origin='lower', cmap='cubehelix') 
plt.xlabel('X') 
plt.ylabel('Y') 
 
x_array = np.arange(0, 1000) 
line_1 = 1 * x_array + 20 * np.sin(0.05*x_array) 
line_2 = x_array - 100 + 20 * np.sin(0.05*x_array) 
 
plt.plot(x_array, line_1, color='red') 
plt.plot(x_array, line_2, color='red') 
 
ax.set_xlim(0, hdu.shape[1]) 
ax.set_ylim(0, hdu.shape[0]) 
 
plt.show() 

我想计算位于两条曲线之间的中值像素值(例如在 y 方向):

我相信聪明的做法是为感兴趣的区域创建一个掩膜。

有没有一种方法可以在不循环遍历图像像素的情况下生成此蒙版?

编辑 1:修改问题提高理解

编辑 2:我更改了示例以更好地表示问题标题(曲线而不是直线)

请您参考如下方法:

生成这种掩码的一种相当直接的方法是使用 numpy.mgrid thingy 本质上为您提供 x 和 y 坐标数组(在那种 2D 情况下),然后可用于使用 lines 的方程式计算掩码。

编辑: 如果您可以使用方程式(例如 f(x,y)<0,其中 f 是您想要的任何函数)或这些方程式的组合来表达掩码,您可以做任何您想做的事情。以下是您的新面具以及一些额外的艺术作品的示例:

import numpy as np 
import matplotlib.pyplot as plt 
 
y,x=np.mgrid[0:1000,0:1000] 
 
#a wiggly ramp 
plt.subplot(221) 
mask0=(y < x + 20 * np.sin(0.05*x)) & (y > x - 100 + 20 * np.sin(0.05*x)) 
plt.imshow(mask0,origin='lower',cmap='gray') 
 
#a ramp 
plt.subplot(222) 
mask1=(y < x) & (x < y+100) 
plt.imshow(mask1,origin='lower',cmap='gray') 
 
#a disk 
plt.subplot(223) 
mask2=(200**2>(x-500)**2+(y-500)**2) 
plt.imshow(mask2,origin='lower',cmap='gray') 
 
#a ying-yang attempt 
plt.subplot(224) 
mask3= (mask2 & (0 < np.sin(3.14*x/250)*100 + 500 - y) & (30**2 < (x-620)**2+(y-500)**2) )| (30**2 > (x-380)**2+(y-500)**2) 
plt.imshow(mask3,origin='lower',cmap='gray') 
 
plt.show() 

输出: