1
votes

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.

1
If it is a greyscale image why not use it as a greyscale image and and change everything below, lets say 10 (almost black) to 255 (white). With in range, you have to define which colors are in valid range using a lower bound and upper bound, then use this as a mask and color that area white. In this tutorial they show you how to filter by color, by upperr bound I would use something close to black (10,10,10) and lower bound just black (0,0,0) since black is not always pure - api55

1 Answers

1
votes

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