我需要将RGBA图像拆分为任意数量的,尺寸尽可能相等的盒子

我曾尝试使用numpy.array_split,但不确定如何在保留RGBA通道的同时使用它

我看了以下问题,它们都没有详细说明如何将图像拆分为n个框,它们引用了如何将图像拆分为预定像素大小的框,或如何将图像拆分为某种形状。

从盒子尺寸和图像尺寸中获得盒子数量似乎是一些简单的数学运算,但我不确定该怎么做。

How to Split Image Into Multiple Pieces in Python

Cutting one image into multiple images using the Python Image Library

Divide image into rectangles information in Python

在尝试根据像素框大小确定框数时,我使用了公式

num_boxes = (img_size[0]*img_size[1])/ (box_size_x * box_size_y)

但这并没有导致图像被正确分割

为了澄清,我希望能够输入大小为(a,b,4)的numpy数组和许多盒子的图像,并以某种形式输出图像(首选np数组,但可以使用)

我非常感谢您的帮助,即使您无法提供完整的方法,也请您提供一些指导。

我努力了
def split_image(image, n_boxes):
    return numpy.array_split(image,n_boxes)
    #doesn't work with colors

def split_image(image, n_boxes):
    box_size = factor_int(n_boxes)
    M = im.shape[0]//box_size[0]
    N = im.shape[1]//box_size[1]

    return [im[x:x+M,y:y+N] for x in range(0,im.shape[0],M) for y in range(0,im.shape[1],N)]

factor_int从Factor an integer to something as close to a square as possible返回尽可能接近正方形的整数

最佳答案

我仍然不确定您输入的内容实际上是图像和盒子的尺寸还是图像和盒子的数量。我也不知道您的问题是决定在哪里剪切图像或知道如何剪切4通道图像,但是这里的某些内容可以帮助您入门。

我从RGBA图像开始-圆圈是透明的,而不是白色的:

python - 将图片分割成任意数量的盒子-LMLPHP

#!/usr/bin/env python3

from PIL import Image
import numpy as np
import math

# Open image and get dimensions
im = Image.open('start.png').convert('RGBA')

# Make Numpy array from image and get height and width
ni = np.array(im)
h ,w = ni.shape[:2]
print(f'Height: {h}, width: {w}')

BOXES = 4
for i in range(BOXES):
    this = ni[:, i*w//BOXES:(i+1)*w//BOXES, :]
    Image.fromarray(this).save(f'box-{i}.png')

您可以更改BOXES,但将其保留为4可获取以下4个输出图像:

python - 将图片分割成任意数量的盒子-LMLPHP [] [] 4 python - 将图片分割成任意数量的盒子-LMLPHP

关于python - 将图片分割成任意数量的盒子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56896878/

10-12 21:56