1

I want to change the colour of a 20 by 20 pixel square anywhere in the image to be purely red. Image data is just an array. For me to change a square to red, i will need to set the red layer to its maximum value and the green and blue layers to zero in the square of interest. Not to sure on how to do this.

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 Answers3

2

To draw a square on the image, you can use Rectangle from matplotlib.

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

If you actually want to change each individual pixel, you could iterate over the rows/columns and set each pixel to [255, 0, 0]. Here's an example (if you go this direction, you'll want to include exception handling for 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

Edit:

A more efficient solution for changing pixel values would be to use an array slice.

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
2
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)
lightalchemist
  • 10,031
  • 4
  • 47
  • 55
1

You can do in this way:

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()
Joe
  • 12,057
  • 5
  • 39
  • 55