[我试图在python中平铺JPG图像。通常,我使用imageMagick ..所以我比wand似乎能完成这项工作...
但是我无法翻译
convert -crop 256x256 +repage big_image.jpg tiles_%d.jpg
有人可以帮我吗?
Python的魔杖库提供了唯一的crop alternative.,使用wand.image.Image[left:right, top:bottom]
可以对新的虚拟像素图像进行分切片。
from wand.image import Image
with Image(filename="big_image.jpg") as img:
i = 0
for h in range(0, img.height, 256):
for w in range(0, img.width, 256):
w_end = w + 256
h_end = h + 256
with img[w:w_end, h:h_end] as chunk:
chunk.save(filename='tiles_{0}.jpg'.format(i))
i += 1
上面的代码将生成许多与+repage
选项匹配的图块图像:
convert -crop 256x256 +repage big_image.jpg tiles_%d.jpg
用于构建功能金字塔样式网络
def image_to_square_tiles(img, SQUARE_SIZE = 256, plot=False, save=False):
"""
Function that splits multi channel channel images into overlapping square tiles (divisible by 128)
:param img: image: multi channel image (NxMxC matrix)
:param number_of_tiles: squared number
:param plot: whether to plot an aimage
:return tiles: named tuple of tiled images (.img) and coordinates (.coords)
------------------------
Examples usage:
_ = image_to_square_tiles(img, SQUARE_SIZE = 512, plot=True)
--------------------------
"""
def get_overlap(l, SQUARE_SIZE):
N_squares = np.ceil(l/SQUARE_SIZE)
pixel_padding = np.remainder(l,SQUARE_SIZE)
if pixel_padding!=0:
overlap = int((SQUARE_SIZE-pixel_padding)//(N_squares-1))
else:
overlap = 0
return overlap
def get_tuples(l, overlap, SQUARE_SIZE):
r = np.arange(0, l-overlap, (SQUARE_SIZE-overlap))
tuples = [(i, i+SQUARE_SIZE) for i in r]
return tuples
[w, h] = img.shape[:2]
assert SQUARE_SIZE%128==0, "has to be a multiple of 128 . i.e. [128,256,384,512,640,768,896,1024]"
w_overlap = get_overlap(w, SQUARE_SIZE)
w_tuples = get_tuples(w, w_overlap, SQUARE_SIZE)
h_overlap = get_overlap(h, SQUARE_SIZE)
h_tuples = get_tuples(h, h_overlap, SQUARE_SIZE)
tile_record = namedtuple("info", "img coords")
tiles = []
for row in range(len(w_tuples)):
for column in range(len(h_tuples)):
#print(row,column)
x1, x2, y1, y2 = *w_tuples[row], *h_tuples[column]
record = tile_record(img[x1:x2, y1:y2], (x1, y1, x2, y2))
tiles.append(record)
if plot:
c = 0
fig, axes = plt.subplots(len(w_tuples), len(h_tuples), figsize=(15,8))
for row in range(len(w_tuples)):
for column in range(len(h_tuples)):
axes[row, column].imshow(tiles[c].img)
#axes[row,column].set_title("ave: {:.3f}".format(np.average(tiles[c].img)))
axes[row,column].axis('off')
c+=1
if save:
plt.savefig("{}.png".format(SQUARE_SIZE), bbox_inches = "tight")
print("h overlap: {}\t w overlap: {}".format(w_overlap, h_overlap))
return tiles