【问题标题】:Split Image into arbitrary number of boxes将图像拆分为任意数量的框
【发布时间】:2019-11-15 17:21:26
【问题描述】:

我需要将 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 返回尽可能接近正方形的整数

【问题讨论】:

  • 您能否编辑您的问题以提供您尝试过的任何代码?
  • 1x1 像素框大小相同,保证覆盖任何矩形图像。请说明您对盒子的真正限制。计算盒子大小是困难的部分;通过矩形坐标切割子图像是微不足道的。
  • 只需找到ab 中较大的那个,然后除以N
  • @9000 我不确定你所说的实际限制是什么意思,我只是想将图像切割成 n 个框(n: 1→ num_pixels)。
  • @MarkSetchell 这些 'a' 和 'b' 值是像素框的 x 和 y 大小吗?

标签: python image numpy opencv image-processing


【解决方案1】:

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

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

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

[] []4

【讨论】:

  • 这里是二维的版本。 columns = 3 rows = 4 for j in range(rows): for i in range(columns): elem = ni[ jw//columns:(j+1)*w//columns, ih//rows:(i+1)*h//rows,:] id=j*columns+i Image.fromarray(elem).save(f'img-{id}.png')
  • 对不起上面的帖子我想在这里发表评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多