user3281831
user3281831

Reputation: 909

Changing black color to white but not white color to black with Python openCV PIL

Im trying to change black pixels to white with opencv in python using cv2 or PIL.

Original picture:

enter image description here

Here is my code:

import cv2
import numpy as np

frame = cv2.imread("numptest/captcha.png")
cv2.imshow('frame',frame)

lower_black = np.array([0,0,0])
upper_black = np.array([1,1,1])
black_mask = cv2.inRange(frame, lower_black, upper_black)
cv2.imshow('mask0',black_mask)
cv2.waitKey()

The result looks like this:

enter image description here

while I would like it to look like this:

enter image description here

I have tried also this code, which does preserve what is inside those rectangles, but works only for exactly RGB 255 255 255, while i need it to work for wider range of RGB.

from PIL import Image
import numpy as np

im = Image.open('numptest/captcha.png')
im = im.convert('RGBA')
data = np.array(im)   
black_areas = (red == 0) & (blue == 0) & (green == 0)
data[..., :-1][black_areas.T] = (255, 255, 255)

im2 = Image.fromarray(data)
im2.show()'

Here is result of second code:

enter image description here

So I dont know, maybe best would be some combination of these codes, I just dont really understand how to use inRange in second code, that would probably solve my problem.

Upvotes: 1

Views: 2759

Answers (1)

user3281831
user3281831

Reputation: 909

Actauly I found answer to my own question while writing the question. I just altered the second code.

this line:

       black_areas = (red == 0) & (blue == 0) & (green == 0)

with this line:

    black_areas = (red < 70) & (blue < 70) & (green < 70)

This is the result:

enter image description here

Upvotes: 1

Related Questions