1

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Ajinkya
  • 1,797
  • 3
  • 24
  • 54
  • Are you asking how to convert a numpy array to a displayable image? [how-do-i-convert-a-numpy-array-to-and-display-an-image](https://stackoverflow.com/questions/2659312/how-do-i-convert-a-numpy-array-to-and-display-an-image) – Patrick Artner Aug 04 '19 at 09:18
  • Or how to use memory-images without storing to disk? [saving-a-numpy-array-as-a-io-bytesio-with-jpg-format](https://stackoverflow.com/questions/39641596/saving-a-numpy-array-as-a-io-bytesio-with-jpg-format) – Patrick Artner Aug 04 '19 at 09:20

1 Answers1

1

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

Ajinkya
  • 1,797
  • 3
  • 24
  • 54