Save image with no background opencv

Viewed 982

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!!!

2 Answers

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)
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

Related