简体   繁体   English

Python 在 x 和 y 轴上每第 n 个像素改变颜色

[英]Python Changing color for every n-th pixel on x and y axis

As the title says, I have to take an image and write code that colors in every n-th pixel on x axis and y axis.正如标题所说,我必须在x轴和y轴上的每个第 n 个像素中拍摄一张图像并编写 colors 的代码。

I've tried using for loops, but it colors in the whole axis line instead of the one pixel that i need.我试过使用 for 循环,但它在整个轴线上是 colors 而不是我需要的一个像素。 I either have to use OpenCV or Pillow for this task.我要么必须使用 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)

This is how it should approximately look like:这应该是大概的样子:

在此处输入图像描述

You really should avoid for loops with image processing in Python.你真的应该避免在 Python 中进行图像处理的for循环。 They are horribly slow and inefficient.它们非常缓慢且效率低下。 As pretty much all image processing suites use Numpy arrays to store images, you should try and use vectorised Numpy access methods such as slicing, indexing and broadcasting:由于几乎所有图像处理套件都使用 Numpy arrays 来存储图像,因此您应该尝试使用矢量化的 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)

在此处输入图像描述


If you want to use PIL/Pillow in place of OpenCV , load and save the image like this:如果您想使用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')

Maybe have a read here about indexing.也许在这里阅读有关索引的信息。

I don't think I've understood your question but here is my answer on what i understood of it.我认为我没有理解您的问题,但这是我对它的理解的回答。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM