Adam C
Adam C

Reputation: 167

OpenCV in Python - Manipulating pixels

I am using python 2.7 and OpenCV to set an image to all white pixels, but it is not working.

Here is my code:

import cv2
import numpy as np

image = cv2.imread("strawberry.jpg") #Load image

imageWidth = image.shape[1] #Get image width
imageHeight = image.shape[0] #Get image height

xPos = 0
yPos = 0

while xPos < imageWidth: #Loop through rows
    while yPos < imageHeight: #Loop through columns

        image.itemset((xPos, yPos, 0), 255) #Set B to 255
        image.itemset((xPos, yPos, 1), 255) #Set G to 255
        image.itemset((xPos, yPos, 2), 255) #Set R to 255

        yPos = yPos + 1 #Increment Y position by 1
    xPos = xPos + 1 #Increment X position by 1
    
cv2.imwrite("result.bmp", image) #Write image to file

print "Done"

I use numpy to set the pixels of the image - but the result.bmp is an exact copy of the original image.

What am I doing wrong?

EDIT:

I know it is a bad idea to iterate over pixels, but what is the non functioning part of my code?

Upvotes: 1

Views: 6639

Answers (2)

Oliver W.
Oliver W.

Reputation: 13459

Aside from the valid suggestion made by @berak, if this is code that you wrote to get to learn the library you want to use, then you've made 2 mistakes:

  1. You forgot to reset the yPos row index counter after the inner while loop
  2. You switched the order of xPos, yPos in itemset.

I guess that your image did change, but it's only on the first row, which you might not see if you don't zoom in. If you change your code like this, it works:

import cv2
import numpy as np

image = cv2.imread("testimage.jpg") #Load image

imageWidth = image.shape[1] #Get image width
imageHeight = image.shape[0] #Get image height

xPos, yPos = 0, 0

while xPos < imageWidth: #Loop through rows
    while yPos < imageHeight: #Loop through columns

        image.itemset((yPos, xPos, 0), 255) #Set B to 255
        image.itemset((yPos, xPos, 1), 255) #Set G to 255
        image.itemset((yPos, xPos, 2), 255) #Set R to 255

        yPos = yPos + 1 #Increment Y position by 1
        
    yPos = 0
    xPos = xPos + 1 #Increment X position by 1

cv2.imwrite("result.bmp", image) #Write image to file

Note that I would also not recommend iterating over an image pixel by pixel, as mentioned before.

Upvotes: 1

berak
berak

Reputation: 39816

rule one with opencv/python: never iterate over pixels, if you can avoid it !

if you wanted to set all of the pixels to (1,2,3), it's as easy as:

image[::] = (1,2,3)

for 'all white':

image[::] = (255,255,255)

Upvotes: 2

Related Questions