【问题标题】:convert and crop image in tiles with python使用python转换和裁剪图块中的图像
【发布时间】:2015-04-14 07:58:53
【问题描述】:

我尝试在 python 中平铺 JPG 图像。通常我使用 imageMagick .. 所以我看到 wand 似乎做了这项工作......

但是我不会翻译

 convert -crop 256x256 +repage big_image.jpg tiles_%d.jpg

有人可以帮我吗?

【问题讨论】:

    标签: python imagemagick crop imagemagick-convert wand


    【解决方案1】:

    Python 的 wand 库提供了独特的 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
    

    【讨论】:

    • 谢谢@emcconville ...如果我想在磁贴名称中添加线条和克隆位置?像chunk.save(filename=myfilename+'tiles_'+chr(h)+'_'+chr(w)+'.jpg'.format(i)) 我猜?但不像,我有一个错误......
    • 是的。只需要重新审视一些字符串格式。喜欢:"{}_tiles_{}_{}.jpg".format(myfilename, h, w),但这取决于你
    【解决方案2】:

    用它来构建特征金字塔风格的网络

    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
    

    【讨论】:

      【解决方案3】:

      如果你想基于 rowsXcols 平铺图像:你可以使用这个:

      def TileImage(image,rows,cols):
      imagename = image
      im = Image.open(imagename) 
      width, height = im.size
      indexrow = 0
      indexcolum = 0
      left = 0
      top = 0
      right = width/col
      buttom = 0
      while(right<=width):    
      
          buttom = height/rows
          top = 0
          indexrow=0  
      
          while(top<height):
              print(f"h : {height}, w : {width}, left : {left},top : {top},right : {right}, buttom   :  {buttom}")
              cropimg= im.crop((left, top, right, buttom)) 
              cropimg.save(imagename + str(indexrow) + str(indexcolum) +".jpg")
              top = buttom
              indexrow += 1
              buttom += height/rows   
      
          indexcolum+=1
          left = right
          right += width/col  
      

      调用这个函数:

      TileImage(r"images/image.JPG",4,4)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        • 2013-12-20
        • 2016-11-22
        • 2011-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多