【问题标题】:Python Changing color for every n-th pixel on x and y axisPython为x和y轴上的每个第n个像素更改颜色
【发布时间】:2020-12-22 13:08:22
【问题描述】:

正如标题所说,我必须拍摄一张图像并编写代码,在x 轴和y 轴上的每个第 n 个像素上着色。

我尝试过使用 for 循环,但它在整个轴线上着色,而不是我需要的一个像素。我要么必须使用 OpenCV 或 Pillow 来完成这项任务。

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

picture = Image.open('e92m3.jpg')

picture_resized = picture.resize( (500,500) )

pixels = picture_resized.load()
#x,y
for i in range(0,500):
    pixels[i,10] = (0,255,0)
for i in range(0,500):
    pixels[10,i] = (255,0,0)

%matplotlib notebook
plt.imshow(picture_resized)

这应该是大概的样子:

【问题讨论】:

标签: python opencv python-imaging-library


【解决方案1】:

在 Python 中进行图像处理时,您确实应该避免 for 循环。它们非常缓慢且效率低下。由于几乎所有图像处理套件都使用 Numpy 数组来存储图像,因此您应该尝试使用向量化的 Numpy 访问方法,例如切片、索引和广播:

import numpy as np
import cv2

# Load image
im = cv2.imread('lena.png')

# Use Numpy indexing to make alternate rows and columns black
im[0::2,0::2] = [0,0,0]
im[1::2,1::2] = [0,0,0]

cv2.imwrite('result.png', im)


如果您想使用 PIL/Pillow 代替 OpenCV,请像这样加载并保存图像:

from PIL import Image

# Load as PIL Image and make into Numpy array
im = np.array(Image.open('lena.png').convert('RGB'))

... process ...

# Make Numpy array back into PIL Image and save
Image.fromarray(im).save('result.png')

也许阅读 here 关于索引。

【讨论】:

    【解决方案2】:

    我认为我没有理解你的问题,但这是我对它的理解的回答。

    def interval_replace(img, offset_x: int=0, interval_x: int, offset_y: int=0, interval_y: int, replace_pxl: tuple):
        for y in range(offset_y, img.shape[0]):
            for x in range(offset_x, img.shape[1]):
                if x % interval_x == 0 and y % interval_y == 0:
                   img[y][x] = replace_pxl
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多