【问题标题】:Optimization Basic Image Processing Python优化基础图像处理 Python
【发布时间】:2020-08-13 19:51:02
【问题描述】:

我正在尝试完成基本的图像处理。这是我的算法:

求 n., n+1., n+2.像素的 RGB 值并根据这些值创建新图像。

我正在获取第一个像素的红色值、第二个像素的绿色值和第三个像素的蓝色值并创建像素。对图像中的每一行都继续此操作。

这是我在 python 中的示例代码:

import glob
import ntpath

import numpy
from PIL import Image

images = glob.glob('balls/*.png')
data_compressed = numpy.zeros((540, 2560, 3), dtype=numpy.uint8)
for image_file in images:

    print(f'Processing [{image_file}]')
    image = Image.open(image_file)
    data = numpy.loadasarray(image)

    for i in range(0, 2559):
        for j in range(0, 539):
            pix_x = j * 3 + 1
            red = data[pix_x - 1, i][0]
            green = data[pix_x, i][1]
            blue = data[pix_x + 1, i][2]
            data_compressed[j, i] = [red, green, blue]

    im = Image.fromarray(data_compressed)
    image_name = ntpath.basename(image_file)
    im.save(f'export/{image_name}')

我的输入和输出图像是 RGB 格式。我的代码每张图片需要 5 秒。我愿意接受任何优化此任务的想法。如果需要,我可以使用 c++ 或任何其他语言。

【问题讨论】:

  • 所有像素都是灰度的还是可以是任何颜色?
  • 可以是任何颜色

标签: python image-processing optimization


【解决方案1】:
data_compressed = np.concatenate((
    np.expand_dims(data[0:-2][:,:,0], axis=2),
    np.expand_dims(data[1:-1][:,:,1], axis=2),
    np.expand_dims(data[2:][:,:,2], axis=2)), axis=2)
  1. Image1:原始图像
  2. Image2:原始图像移动了一个像素
  3. Image3:原始图像移动了两个像素
  4. 将 Image1 的通道 0、Image2 的通道 1 和 Image3 的通道 3 连接起来。

示例

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

image = Image.open("Lenna.png")
data = numpy.asarray(image)

data_compressed = np.concatenate((
    np.expand_dims(data[0:-2][:,:,0], axis=2),
    np.expand_dims(data[1:-1][:,:,1], axis=2),
    np.expand_dims(data[2:][:,:,2], axis=2)), axis=2)

new_image = Image.fromarray(data_compressed)

如果您想要跨越 3 个像素再次计算下一个像素,那么您可以使用 numpy 切片

new_image = Image.fromarray(data_compressed[:, ::3])

原图:

3 步长的变换图像:

【讨论】:

  • 谢谢。它比我的代码快得多,但它适用于所有图像。我的输入图像是:2560 x 1620,最终图像是 2560 x 540。所以它需要在 1 个轴上工作,而不是两个。是否可以在 1 轴上进行。
  • 感谢它的魅力。我的旧代码是每张图片 5 秒现在每张图片 0.12 秒。
  • 导出的图像在一维中丢失 2 个像素。你注意到了吗?示例图像 220x220 => 最终图像 74 x 218
【解决方案2】:

好吧,如果只是想加快速度,您应该看看 Cython 模块。它允许您指定不同变量的类型,然后将脚本编译为正常运行的 c 代码。当涉及到时间复杂度时,这通常可以带来很大的改进。

【讨论】:

    【解决方案3】:

    使用普通的 python,你能做的只有这么多。这是一个小的优化,它可以帮助一点,因为它会分配更少的内存。否则,我会按照前面所说的或使用其他语言来查看 Cython/Numba。

    data_compressed[j, i, 0] = data[pix_x - 1, i][0]
    data_compressed[j, i, 1] = data[pix_x, i][1]
    data_compressed[j, i, 2] = data[pix_x + 1, i][2]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-26
      • 2012-07-20
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多