python - 将图像分割成任意数量的框

标签 python image numpy opencv image-processing

我需要将 RGBA 图像分割成任意数量的大小尽可能相等的框

我尝试使用 numpy.array_split,但不确定如何在保留 RGBA channel 的同时做到这一点

我查看了以下问题,没有一个详细说明如何将图像分割成 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 channel 图像,但也许这里的某些内容可以帮助您入门。

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

enter image description here

#!/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 个输出图像:

enter image description here [enter image description here ] [enter image description here ] 4 enter image description here

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

相关文章:

wpf - 多个目标名称的相同动画

html - 导航按钮下方没有空格

python - else 和 finally 在异常处理中的目的

python - Django多表继承和 Graphite 烯

python - 如何知道ui窗体中的哪个qwidget在pyqt中获得了焦点

python - 为什么我不在 for 循环中递增?

python - 添加到 Pandas DataFrame 时出现 datetime64 错误

python - 查找数组中下一个最大值的更快方法

image - OpenCV : Transparent area of imported . png 文件现在是白色的

python - Pandas :减去两列并将结果保存为绝对值