4

I want to create a small scrypt that creates png images with no background. I've reading some information and I'm not sure if this is possible with opencv. (Sorry if it is a silly question but I'm newbie with this library).

Create an image is easy,

import cv2
import numpy as np

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Drawing a circle
circle = cv2.circle(img,(256,256), 63, (0,0,255), -1)

# 
cv2.imwrite('circle.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

But, it is possible save it without background? In this example, it is possible just save the circle?

Thank you very much!!!

Lleims
  • 1,275
  • 12
  • 39
  • https://stackoverflow.com/questions/40527769/removing-black-background-and-make-transparent-from-grabcut-output-in-python-ope – Shkar Sardar Apr 08 '20 at 17:18
  • 1
    What do you mean by no background? Do you mean transparent? Even transparency is a background. If you want your red circle on a transparent background make a binary mask for the circle and put that into the alpha channel of the image of the red circle. – fmw42 Apr 08 '20 at 23:11

2 Answers2

4

I have added transparency channel(or layer) to the image here in the code below. It will give a feel that there is nothing in the background.

import cv2
import numpy as np

# Create a black image
img = np.zeros((512,512, 4), np.uint8)

# Drawing a circle
circle = cv2.circle(img, (256,256), 63, (0,0,255, 255), -1)

# 
cv2.imwrite('circle.png',img)
Alok Nayak
  • 2,381
  • 22
  • 28
2
import cv2
import numpy as np

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Drawing a circle
circle = cv2.circle(img, (256,256), 63, (0,0,255), -1)

# Convert circle to grayscale
gray = cv2.cvtColor(circle, cv2.COLOR_BGR2GRAY)

# Threshold to make a mask
mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# Put mask into alpha channel of Circle
result = np.dstack((circle, mask))

# 
cv2.imwrite('circle.png',result)


enter image description here

fmw42
  • 46,825
  • 10
  • 62
  • 80