【问题标题】:How does one invert an area of an image with python?如何用 python 反转图像的区域?
【发布时间】:2022-11-19 02:16:13
【问题描述】:

我被提示修改我们的一个过滤器,以便我们可以指定图像的哪一部分应该被修改。 row1 和 col1 :左上坐标要修改的矩形 row2 和 col2:要修改的矩形的右下坐标

我已经尝试过,但没有用。

这是我到目前为止所尝试的

`

def invertspot(pic, row1, col1, row2, col2):
      # Go through each row and column
      for row in range(pic.height):
        for col in range(pic.width):
          # Gets a pixel at row/col
          pixel = pic.pixels[row1][col1][row2][col2]

          # Get the RGB values of this pixel
          red = pixel.red
          green = pixel.green
          blue = pixel.blue
          # Resave them and get the inverse by subtracting 255 from the value of the
          #color
          pixel.red = 255 - red
          pixel.green = 255 - green
          pixel.blue = 255 - blue

          # Finally, reset the pixel stored at that spot
          pic.pixels[row][col] = pixel

`

【问题讨论】:

  • 您使用哪些库来处理图像?为问题添加适当的标签。

标签: python python-imaging-library


【解决方案1】:

我会在 numpy 中这样做。更轻松,跑得更快。

from PIL import Image
import numpy as np

img = Image.open("test186_img.jpg")

def invertspot(pic, row1, col1, row2, col2):
    array = np.array(img)
    subset = array[row1:row2, col1:col2]
    subset = 255 - subset
    array[row1:row2, col1:col2] = subset
    return Image.fromarray(array)
invertspot(img, 200, 600, 500, 800)

示例输出:

(图片来源:Wikipedia

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    相关资源
    最近更新 更多