我有一系列来自自动显微镜程序的图像,从96孔板获取图像(下图)。每个图像都命名为:
<Well name>_s<site number>.tif
96孔板的每个孔进一步细分为位点,位点以X×Y矩阵排列,并且数字逐行排列(下图)。
例如,将命名96孔板中左上孔的第(10,9)位点的图像
A01_s90.tif
。
将图像拼接在一起的最Pythonic方法是什么?我目前正在使用OpenCV加载图像并在四个numpy.concatenate
循环中调用for
,但这看起来非常笨拙。
答案 0 :(得分:3)
类似下面的代码?我假设它是问题的拼接,而不是文件名和井/站点索引之间的转换。
import numpy as np
import matplotlib.pyplot as plt
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 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(block=False)
raw_input("Enter")
答案 1 :(得分:0)
Han-Kwang Nienhuys的答案并没有消除困扰OP的四个嵌套for循环。
这是他的答案的修改版本,只有一个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")