在python中更改像素的颜色

在python中更改像素的颜色,python,arrays,numpy,pixel,Python,Arrays,Numpy,Pixel,我想把图像中任意一个20×20像素正方形的颜色改成纯红色。图像数据只是一个数组。要将正方形更改为红色,我需要在感兴趣的正方形中将红色层设置为其最大值,将绿色和蓝色层设置为零。不知道该怎么做 import numpy as np import matplotlib.pyplot as plt imageArray = plt.imread('earth.jpg') print('type of imageArray is ', type(imArray)) print('shape of ima

我想把图像中任意一个20×20像素正方形的颜色改成纯红色。图像数据只是一个数组。要将正方形更改为红色,我需要在感兴趣的正方形中将红色层设置为其最大值,将绿色和蓝色层设置为零。不知道该怎么做

import numpy as np
import matplotlib.pyplot as plt

imageArray = plt.imread('earth.jpg')
print('type of imageArray is ', type(imArray))
print('shape of imageArray is ', imArray.shape)

fig = plt.figure()
plt.imshow(imageArray)

要在图像上绘制正方形,可以使用matplotlib中的
矩形

如果确实要更改每个像素,可以迭代行/列,并将每个像素设置为[255,0,0]。下面是一个示例(如果您朝这个方向走,您将希望包括IndexError的异常处理):

编辑:

更改像素值的更有效解决方案是使用阵列切片

def drawRedSquare(image, location, size):

    x,y = location
    w,h = size
    image[y:y+h,x:x+w] = np.ones((w,h,3)) * [255,0,0]

    return image

您可以这样做:

from PIL import Image
picture = Image.open(your_image)
pixels = picture.load()

for i in range(10,30): # your range and position
    for j in range(10,30):
        pixels[i,j] = (255, 0, 0)

picture.show()

你是怎么看这张图片的?
def drawRedSquare(image, location, size):

    x,y = location
    w,h = size
    image[y:y+h,x:x+w] = np.ones((w,h,3)) * [255,0,0]

    return image
from PIL import Image
picture = Image.open(your_image)
pixels = picture.load()

for i in range(10,30): # your range and position
    for j in range(10,30):
        pixels[i,j] = (255, 0, 0)

picture.show()
import numpy as np
import matplotlib.pyplot as plt

imageArray = plt.imread('earth.jpg')

# Don't use loops. Just use image slicing since imageArray is a Numpy array.
# (i, j) is the row and col index of the top left corner of square.
imageArray[i:i + 20, j:j + 20] = (255, 0, 0)