Ajinkya
Ajinkya

Reputation: 1887

How to perform OpenCV transform without explicitly saving the image

I have input image b, when I do

cv2.imwrite("contor.jpg", b)

I get

enter image description here

I want to keep only the white pixels in image b and remove the rest to do that I do:

im = cv2.imread("contor.jpg")

im[np.any(im != [255, 255, 255], axis=-1)] = [0,0,0]

cv2.imwrite('box_mask.png', im)

After this I get output: enter image description here

My question is every time to get an output as shown above I Must save image b. by using

cv2.imwrite("contor.jpg", b)

and then read it back using

im = cv2.imread("contor.jpg")

and then change all the non white pixels to black. I want to do this without saving the image and reading it back every time

To do this I did:

im=b.copy()

im[np.any(im != [255, 255, 255], axis=-1)] = [0,0,0]

cv2.imwrite('box_mask.png', im)

For which I get this error:

python3 demo2.py --image 1.jpg 
Traceback (most recent call last):
  File "demo2.py", line 123, in <module>
    im[np.any(im != [255, 255, 255], axis=-1)] = [0,0,0]
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (1,512,640)

How do I avoid saving image b every time and re-reading it? I want to directly manipulate b and display final results.

Upvotes: 1

Views: 793

Answers (1)

Ajinkya
Ajinkya

Reputation: 1887

okay this was relatively easy. I referred to Replace all the colors of a photo except from the existing black and white pixels PYTHON

and by doing :

im=b.copy()
im[im != 255] = 0

cv2.imshow("out.jpg",im)
cv2.waitKey(0)

I solved the issue

Upvotes: 1

Related Questions