在python中更改像素的颜色

时间:2018-08-17 05:21:44

标签: python arrays numpy pixel

我想将图像中任何地方的20 x 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)

3 个答案:

答案 0 :(得分:2)

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

请参见matplotlib: how to draw a rectangle on image

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

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

fig, ax = plt.subplots(1)

plt.imshow(imageArray)

square = patches.Rectangle((100,100), 20,20, color='RED')
ax.add_patch(square)

plt.show()

如果您实际上要更改每个像素,则可以遍历行/列,并将每个像素设置为[255,0,0]。这是一个示例(如果朝这个方向发展,您将要包括IndexError的异常处理):

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def drawRedSquare(image, location, size):

    x,y = location
    w,h = size

    for row in range(h):
        for col in range(w):
            image[row+y][col+x] = [255, 0, 0]

    return image

imageArray = np.array(plt.imread('earth.jpg'), dtype=np.uint8)
print('type of imageArray is ', type(imageArray))
print('shape of imageArray is ', imageArray.shape)

imArray = drawRedSquare(imageArray, (100,100), (20,20))

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

Result

编辑:

一种更有效的更改像素值的方法是使用数组切片。

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

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

您可以通过以下方式进行:

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()
相关问题