将一系列图像缝合在一起的最具python风格的方法
我有一组来自自动显微镜程序的图像,该程序从96孔板获取图像(下图)。每个图像的名称为:将一系列图像缝合在一起的最具python风格的方法,python,image,opencv,numpy,Python,Image,Opencv,Numpy,我有一组来自自动显微镜程序的图像,该程序从96孔板获取图像(下图)。每个图像的名称为: \u.tif 96孔板的每个孔进一步细分为多个位置,这些位置按X X X Y矩阵排列,编号逐行排列(下图) 例如,96孔板中左上井第(10,9)个位置的图像将命名为 A01_s90.tif 什么是将图像缝合在一起的最适合的方法?我目前正在使用OpenCV加载图像并调用numpy。在四个循环中连接,但这似乎非常笨拙。类似于下面的代码?我假设问题在于缝合,而不是文件名和井/场地索引之间的转换 import n
\u.tif
96孔板的每个孔进一步细分为多个位置,这些位置按X X X Y矩阵排列,编号逐行排列(下图)
例如,96孔板中左上井第(10,9)个位置的图像将命名为
A01_s90.tif
什么是将图像缝合在一起的最适合的方法?我目前正在使用OpenCV加载图像并调用
numpy。在四个循环中连接,但这似乎非常笨拙。类似于下面的代码?我假设问题在于缝合,而不是文件名和井/场地索引之间的转换
import numpy as np
import matplotlib.pyplot as plt
img_ysize, img_xsize = 20, 20 # size of single image
my, mx = 10, 10 # x/y grid of sites per well
ny, nx = 8, 12 # x/y grid of wells per plate
wgap = 20 # pixels gap between wells
stitched_x, stitched_y = (wgap+mx*img_xsize)*nx, (wgap+my*img_ysize)*ny
img_stitched = np.zeros((stitched_y, stitched_x), dtype=np.uint8)
def add_img(mxi, myi, nxi, nyi, img):
assert img.shape == (img_ysize, img_xsize)
xi = nxi*(mx*img_xsize + wgap) + mxi*img_xsize
yi = nyi*(my*img_ysize + wgap) + myi*img_ysize
img_stitched[yi:yi+img_ysize,xi:xi+img_xsize] = img
for nxi in range(nx):
for nyi in range(ny):
for mxi in range(mx):
for myi in range(my):
# ... get image data
img = np.random.randint(0,255) * np.ones((img_ysize, img_xsize), dtype=np.uint8)
add_img(mxi, myi, nxi, nyi, img)
plt.imshow(img_stitched)
plt.colorbar()
plt.show()
Han Kwang Nienhuys的答案并没有消除四个嵌套的for循环,这困扰了OP
以下是他的答案的修改版本,只有一个for循环:
import numpy as np
import matplotlib.pyplot as plt
from itertools import product
img_xsize, img_ysize = 20, 20 # size of single image
mx, my = 10, 10 # x/y grid of sites per well
nx, ny = 12, 8 # x/y grid of wells per plate
wgap = 20 # pixels gap between wells
stitched_x, stitched_y = (wgap+mx*img_xsize)*nx, (wgap+my*img_ysize)*ny
img_stitched = np.zeros((stitched_y, stitched_x), dtype=np.uint8)
def add_img(mxi, myi, nxi, nyi, img):
assert img.shape == (img_ysize, img_xsize)
xi = nxi*(mx*img_xsize + wgap) + mxi*img_xsize
yi = nyi*(my*img_ysize + wgap) + myi*img_ysize
img_stitched[yi:yi+img_ysize,xi:xi+img_xsize] = img
for nxi, nyi, mxi, myi in product(range(nx), range(ny), range(mx), range(my)):
# ... get image data
img = np.random.randint(0,255) * np.ones((img_ysize, img_xsize), dtype=np.uint8)
add_img(mxi, myi, nxi, nyi, img)
plt.imshow(img_stitched)
plt.colorbar()
plt.show(block=False)
raw_input("Enter")
在for
循环中串联数组效率非常低,因为它会在每次调用时强制执行数据的副本。您最好在列表
中累积子数组,并在外为
循环连接它们,或者初始化一个与最终图像大小相同的大数组,并使用切片索引将子数组写入其中。此算法确实比以前基于实现的级联算法快得多,并且从代码角度来看也更整洁。