【问题标题】:Change a colour of a pixel in python在python中更改像素的颜色
【发布时间】:2019-01-24 02:37:51
【问题描述】:

我想将图像中任意位置的 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)

【问题讨论】:

  • 你看图怎么样?

标签: python arrays numpy pixel


【解决方案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】:

    要在图像上绘制一个正方形,您可以使用 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
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        相关资源
        最近更新 更多