Home > Net >  Changing the color of each 10th and 11th pixel on image
Changing the color of each 10th and 11th pixel on image

Time:11-23

I have a problem related to cv2. I am trying to change a color for each 10th pixel on even row and each 11th pixel on odd row to the red. I am trying to select a specific row but I cannot. Please help

import cv2
import matplotlib.pyplot as plt
# read image
image = cv2.imread('2161382.jpg')
im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# resize image
resized_img = cv2.resize(im_rgb,(500,500))
img_width = resized_img.shape[1]
img_height = resized_img.shape[0]

# Change individual pixel value (y,x)
resized_img[200, 10] = (255,0,0)
for row in resized_img:
    if row.all() % 2 == 0:
        resized_img[:,row   11] = (255,0,0)
            

    
# On your own create a cycle where you can change the color of every N-th pixel on the odd row 
# and every M-th pixel on the even row to a different colour 
                      
%matplotlib notebook
plt.figure(figsize=(10,10))
plt.imshow(resized_img)

CodePudding user response:

You need to check the row number. row.all doesn't do that. This works:

# Change individual pixel value (y,x)
resized_img[200, 10] = (255,0,0)
for y,row in enumerate(resized_img):
    if y % 2:
        row[11] = (255,0,0)
    else:
        row[10] = (255,0,0)

CodePudding user response:

You don't want loops at all, you want indexing which is miles faster and simpler. The indices are set using:

array[START:END:STEP]

so you want:

# Make image of 4 rows 22 columns of zeroes
im = np.zeros((4,22), np.uint8)

That looks like this:

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
      dtype=uint8)

Now change some values using indexing:

# Start at row 0 and on every 2nd row, set every 10th pixel to 7
im[0::2,::10] = 7

# Start at row 1 and on every 2nd row, set every 11th pixel to 9
im[1::2,::11] = 9

Now it looks like this:

array([[7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0],
       [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0],
       [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
      dtype=uint8)

If you have a 3-channel RGB image and you want to set R, G and B, you could add a third, explicit index:

im[::2, ::10, :] = [255,0,0]

Or you could omit it and remain implicit (thanks @Reti43):

im[::2, ::10] = [255,0,0]
  • Related