goddess
goddess

Reputation: 31

Why doesn't python openCV change background colors in the way I expect it to?

I am just starting out with opencv in python3.7.

I am trying to change every color pixel of a gray picture. for example, a pixel with value 1، equal to 254 or pixel with value 30, equal to (255-30)=225 and etc. my code is working correctly, but one thing is wrong: background of my picture is dark and black, I expect شfter executing the code the background to be light and white. but the background does not change.

import cv2 as cv
img2 = cv.imread('2.JPG')
print(img2.shape)
image2 = img2[0::2, 0::2]
for i in range(image2.shape[0]):
    for j in range(image2.shape[1]):
        for k in range(256):
            if image2[i, j, 2] == k:
                image2[i, j] = 255 - k

cv.imwrite('img2.JPG', image2)
cv.imshow('img2', image2)
cv.waitKey()

Upvotes: 0

Views: 76

Answers (1)

Masoud
Masoud

Reputation: 1280

From the logic, it appears you want to invert grayscale image. you can either use image2 = 255 - image2 or image2 = cv2.bitwise_not(image2).

import cv2 as cv

img2 = cv.imread('2.jpg', 0)
image2 = img2[0::2,0::2] #downsampling
image2 = 255 - image2
# image2 = cv.bitwise_not(image2)
cv.imwrite('img2.JPG', image2)
cv.imshow('img2', image2)
cv.waitKey()

Upvotes: 2

Related Questions