python - 改变python中像素的颜色

标签 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)

最佳答案

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

参见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

关于python - 改变python中像素的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51888836/

相关文章:

python - python包开发如何实现跨平台持续集成?

arrays - F# 扫描缓冲区,找到以\c\f 开头且后面不跟逗号的最后一部分

python - NLTK 情感维德 : build pie chart with scores

php - mysql like 子句不适用于数组 php

python - 来自表示 RGB 图像的 float 组的初始 CV::MAT

Python+OpenCV : cv2. 写入

python - 如何从预训练模型保存的h5文件中找到层数?

python-3.x - 如何计算数据帧列中 >=3 个连续 1 值的出现次数

python - 压缩到python中的特定目录

参数大小向量的python符号求和与微分