如何在 tiff 图像上绘制规则网格线?我想在图像上为每个间隔(比如 100 x 100 像素)绘制规则方形网格,并将其与图纸一起保存。我还需要将每个网格 id 覆盖为 '1'、'2'、...在每个网格框的中间。
问问题
23967 次
3 回答
29
您将需要安装 python 映像库 (PIL)。(见这里https://pypi.python.org/pypi/PIL)。有关安装 PIL 方法的示例,请参阅这些答案:答案 1,答案 2
正确,安装后,以下代码应该可以满足您的要求:
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
try:
from PIL import Image
except ImportError:
import Image
# Open image file
image = Image.open('myImage.tiff')
my_dpi=300.
# Set up figure
fig=plt.figure(figsize=(float(image.size[0])/my_dpi,float(image.size[1])/my_dpi),dpi=my_dpi)
ax=fig.add_subplot(111)
# Remove whitespace from around the image
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
# Set the gridding interval: here we use the major tick interval
myInterval=100.
loc = plticker.MultipleLocator(base=myInterval)
ax.xaxis.set_major_locator(loc)
ax.yaxis.set_major_locator(loc)
# Add the grid
ax.grid(which='major', axis='both', linestyle='-')
# Add the image
ax.imshow(image)
# Find number of gridsquares in x and y direction
nx=abs(int(float(ax.get_xlim()[1]-ax.get_xlim()[0])/float(myInterval)))
ny=abs(int(float(ax.get_ylim()[1]-ax.get_ylim()[0])/float(myInterval)))
# Add some labels to the gridsquares
for j in range(ny):
y=myInterval/2+j*myInterval
for i in range(nx):
x=myInterval/2.+float(i)*myInterval
ax.text(x,y,'{:d}'.format(i+j*nx),color='w',ha='center',va='center')
# Save the figure
fig.savefig('myImageGrid.tiff',dpi=my_dpi)
如果在grace_hopper.png
示例文件中使用它,将产生以下输出:
于 2013-12-09T12:57:28.457 回答
21
这可以通过以网格间隔循环图像数据在两行中有效地完成。以 SIPI 数据库中的规范图像为例
import pylab as plt
# Load the image
img = plt.imread("lena512color.tiff")
# Grid lines at these intervals (in pixels)
# dx and dy can be different
dx, dy = 100,100
# Custom (rgb) grid color
grid_color = [0,0,0]
# Modify the image to include the grid
img[:,::dy,:] = grid_color
img[::dx,:,:] = grid_color
# Show the result
plt.imshow(img)
plt.show()
@tom 的答案可能更强大,因为它与 matplotlib 库一起使用。为了简单起见,我将保留此示例。
于 2013-12-09T14:34:35.830 回答
0
让我把它留在这里
def draw_grid(image, line_space=20):
H, W = image.shape
image[0:H:line_space] = 1
image[:, 0:W:line_space] = 1
于 2021-07-09T10:27:09.427 回答