Problem about Background transparent .png format OpenCV with Python












1















I'm studying on OpenCV with Python. I tried to change a color of picture in PNG format, but I have got some problem with PNG background (The image has transparent background).



When I change it to grayscale, the background has changed to black -- my picture is not transparent anymore. What I desire is to keep the transparent background of picture.





Original image:





My code:



img = cv2.imread('line.png',cv2.IMREAD_UNCHANGED)
cv2.imshow('line',img)
cv2.waitKey()


Output image:





Desired output:





The white color around the border image should be transparent. How I can do this?










share|improve this question

























  • I think there are a few problems mixed together here. First of all, if you use imshow, then the transparent areas will be black (since that's the background used -- the window itself isn't transparent). Next, even though PNG supports grayscale + alpha, I'm not aware of any way to save such an image using OpenCV.

    – Dan Mašek
    Nov 19 '18 at 21:32
















1















I'm studying on OpenCV with Python. I tried to change a color of picture in PNG format, but I have got some problem with PNG background (The image has transparent background).



When I change it to grayscale, the background has changed to black -- my picture is not transparent anymore. What I desire is to keep the transparent background of picture.





Original image:





My code:



img = cv2.imread('line.png',cv2.IMREAD_UNCHANGED)
cv2.imshow('line',img)
cv2.waitKey()


Output image:





Desired output:





The white color around the border image should be transparent. How I can do this?










share|improve this question

























  • I think there are a few problems mixed together here. First of all, if you use imshow, then the transparent areas will be black (since that's the background used -- the window itself isn't transparent). Next, even though PNG supports grayscale + alpha, I'm not aware of any way to save such an image using OpenCV.

    – Dan Mašek
    Nov 19 '18 at 21:32














1












1








1


2






I'm studying on OpenCV with Python. I tried to change a color of picture in PNG format, but I have got some problem with PNG background (The image has transparent background).



When I change it to grayscale, the background has changed to black -- my picture is not transparent anymore. What I desire is to keep the transparent background of picture.





Original image:





My code:



img = cv2.imread('line.png',cv2.IMREAD_UNCHANGED)
cv2.imshow('line',img)
cv2.waitKey()


Output image:





Desired output:





The white color around the border image should be transparent. How I can do this?










share|improve this question
















I'm studying on OpenCV with Python. I tried to change a color of picture in PNG format, but I have got some problem with PNG background (The image has transparent background).



When I change it to grayscale, the background has changed to black -- my picture is not transparent anymore. What I desire is to keep the transparent background of picture.





Original image:





My code:



img = cv2.imread('line.png',cv2.IMREAD_UNCHANGED)
cv2.imshow('line',img)
cv2.waitKey()


Output image:





Desired output:





The white color around the border image should be transparent. How I can do this?







python python-3.x image opencv png






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 21:53









Dan Mašek

8,95032647




8,95032647










asked Nov 19 '18 at 18:04









lycalyca

325




325













  • I think there are a few problems mixed together here. First of all, if you use imshow, then the transparent areas will be black (since that's the background used -- the window itself isn't transparent). Next, even though PNG supports grayscale + alpha, I'm not aware of any way to save such an image using OpenCV.

    – Dan Mašek
    Nov 19 '18 at 21:32



















  • I think there are a few problems mixed together here. First of all, if you use imshow, then the transparent areas will be black (since that's the background used -- the window itself isn't transparent). Next, even though PNG supports grayscale + alpha, I'm not aware of any way to save such an image using OpenCV.

    – Dan Mašek
    Nov 19 '18 at 21:32

















I think there are a few problems mixed together here. First of all, if you use imshow, then the transparent areas will be black (since that's the background used -- the window itself isn't transparent). Next, even though PNG supports grayscale + alpha, I'm not aware of any way to save such an image using OpenCV.

– Dan Mašek
Nov 19 '18 at 21:32





I think there are a few problems mixed together here. First of all, if you use imshow, then the transparent areas will be black (since that's the background used -- the window itself isn't transparent). Next, even though PNG supports grayscale + alpha, I'm not aware of any way to save such an image using OpenCV.

– Dan Mašek
Nov 19 '18 at 21:32












2 Answers
2






active

oldest

votes


















0














First, let me mention that if you display an image with alpha transparency using cv2.imshow then the transparent areas are going to be black.





Since your input image already contains an alpha channel, the solution is simple -- just reuse the alpha channel.



There's a slight problem -- even though PNG format allows to have grayscale with alpha channel, AFAIK there is no way to write such an image with OpenCV.



Therefore the solution is straightforward: Take the processed grayscale image, convert it back to BGR, add the original alpha channel, and save the result.



Since we're in Python, and therefore the image is represented as a numpy array, we can use array indexing to extract the channels we need. numpy.dstack allows us to add the alpha channel easily.





Sample code:



import cv2
import numpy as np

src = cv2.imread('51IgH.png', cv2.IMREAD_UNCHANGED)

bgr = src[:,:,:3] # Channels 0..2
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# Some sort of processing...

bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
alpha = src[:,:,3] # Channel 3
result = np.dstack([bgr, alpha]) # Add the alpha channel

cv2.imwrite('51IgH_result.png', result)


Result:





Once more on different background, so you can see it's really transparent:










share|improve this answer
























  • what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

    – lyca
    Nov 21 '18 at 16:09











  • @lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

    – Dan Mašek
    Nov 21 '18 at 23:53





















0














You have to add a fourth channel in your array so that the transparency information can be encoded in the alpha channel.



Here is a python code example:



import cv2
file_name = "source.png"

src = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)

# Save the transparency channel alpha
*_, alpha = cv2.split(src)

gray_layer = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# ... Your image processing

# Duplicate the grayscale image to mimic the BGR image and finally add the transparency
dst = cv2.merge((gray_layer, gray_layer, gray_layer, alpha))
cv2.imwrite("result.png", dst)


Result for grey image:



Grey image with transparency



Result for BGR image:








share|improve this answer


























  • you have example ?

    – lyca
    Nov 19 '18 at 18:16











  • Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

    – Dan Mašek
    Nov 19 '18 at 21:24











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53380318%2fproblem-about-background-transparent-png-format-opencv-with-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














First, let me mention that if you display an image with alpha transparency using cv2.imshow then the transparent areas are going to be black.





Since your input image already contains an alpha channel, the solution is simple -- just reuse the alpha channel.



There's a slight problem -- even though PNG format allows to have grayscale with alpha channel, AFAIK there is no way to write such an image with OpenCV.



Therefore the solution is straightforward: Take the processed grayscale image, convert it back to BGR, add the original alpha channel, and save the result.



Since we're in Python, and therefore the image is represented as a numpy array, we can use array indexing to extract the channels we need. numpy.dstack allows us to add the alpha channel easily.





Sample code:



import cv2
import numpy as np

src = cv2.imread('51IgH.png', cv2.IMREAD_UNCHANGED)

bgr = src[:,:,:3] # Channels 0..2
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# Some sort of processing...

bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
alpha = src[:,:,3] # Channel 3
result = np.dstack([bgr, alpha]) # Add the alpha channel

cv2.imwrite('51IgH_result.png', result)


Result:





Once more on different background, so you can see it's really transparent:










share|improve this answer
























  • what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

    – lyca
    Nov 21 '18 at 16:09











  • @lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

    – Dan Mašek
    Nov 21 '18 at 23:53


















0














First, let me mention that if you display an image with alpha transparency using cv2.imshow then the transparent areas are going to be black.





Since your input image already contains an alpha channel, the solution is simple -- just reuse the alpha channel.



There's a slight problem -- even though PNG format allows to have grayscale with alpha channel, AFAIK there is no way to write such an image with OpenCV.



Therefore the solution is straightforward: Take the processed grayscale image, convert it back to BGR, add the original alpha channel, and save the result.



Since we're in Python, and therefore the image is represented as a numpy array, we can use array indexing to extract the channels we need. numpy.dstack allows us to add the alpha channel easily.





Sample code:



import cv2
import numpy as np

src = cv2.imread('51IgH.png', cv2.IMREAD_UNCHANGED)

bgr = src[:,:,:3] # Channels 0..2
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# Some sort of processing...

bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
alpha = src[:,:,3] # Channel 3
result = np.dstack([bgr, alpha]) # Add the alpha channel

cv2.imwrite('51IgH_result.png', result)


Result:





Once more on different background, so you can see it's really transparent:










share|improve this answer
























  • what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

    – lyca
    Nov 21 '18 at 16:09











  • @lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

    – Dan Mašek
    Nov 21 '18 at 23:53
















0












0








0







First, let me mention that if you display an image with alpha transparency using cv2.imshow then the transparent areas are going to be black.





Since your input image already contains an alpha channel, the solution is simple -- just reuse the alpha channel.



There's a slight problem -- even though PNG format allows to have grayscale with alpha channel, AFAIK there is no way to write such an image with OpenCV.



Therefore the solution is straightforward: Take the processed grayscale image, convert it back to BGR, add the original alpha channel, and save the result.



Since we're in Python, and therefore the image is represented as a numpy array, we can use array indexing to extract the channels we need. numpy.dstack allows us to add the alpha channel easily.





Sample code:



import cv2
import numpy as np

src = cv2.imread('51IgH.png', cv2.IMREAD_UNCHANGED)

bgr = src[:,:,:3] # Channels 0..2
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# Some sort of processing...

bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
alpha = src[:,:,3] # Channel 3
result = np.dstack([bgr, alpha]) # Add the alpha channel

cv2.imwrite('51IgH_result.png', result)


Result:





Once more on different background, so you can see it's really transparent:










share|improve this answer













First, let me mention that if you display an image with alpha transparency using cv2.imshow then the transparent areas are going to be black.





Since your input image already contains an alpha channel, the solution is simple -- just reuse the alpha channel.



There's a slight problem -- even though PNG format allows to have grayscale with alpha channel, AFAIK there is no way to write such an image with OpenCV.



Therefore the solution is straightforward: Take the processed grayscale image, convert it back to BGR, add the original alpha channel, and save the result.



Since we're in Python, and therefore the image is represented as a numpy array, we can use array indexing to extract the channels we need. numpy.dstack allows us to add the alpha channel easily.





Sample code:



import cv2
import numpy as np

src = cv2.imread('51IgH.png', cv2.IMREAD_UNCHANGED)

bgr = src[:,:,:3] # Channels 0..2
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)

# Some sort of processing...

bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
alpha = src[:,:,3] # Channel 3
result = np.dstack([bgr, alpha]) # Add the alpha channel

cv2.imwrite('51IgH_result.png', result)


Result:





Once more on different background, so you can see it's really transparent:











share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 19 '18 at 21:48









Dan MašekDan Mašek

8,95032647




8,95032647













  • what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

    – lyca
    Nov 21 '18 at 16:09











  • @lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

    – Dan Mašek
    Nov 21 '18 at 23:53





















  • what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

    – lyca
    Nov 21 '18 at 16:09











  • @lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

    – Dan Mašek
    Nov 21 '18 at 23:53



















what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

– lyca
Nov 21 '18 at 16:09





what is meaning of src[: , : , :3] . why the last index is must be :3 only ?

– lyca
Nov 21 '18 at 16:09













@lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

– Dan Mašek
Nov 21 '18 at 23:53







@lyca That's the array indexing I mention in the answer -- IMHO it's quite worth taking some time to read that documentation page. In this case it means "give me all the columns, all the rows and all the channels up to (and not including) 3". NB: Remember indexing starts at 0. | A transparent image is a 4 channel image, in this case the channels being Blue (0), Green (1), Red (2), Alpha transparency (3). So that command basically gets rid of the transparency channel, and lets us work only on the colour info.

– Dan Mašek
Nov 21 '18 at 23:53















0














You have to add a fourth channel in your array so that the transparency information can be encoded in the alpha channel.



Here is a python code example:



import cv2
file_name = "source.png"

src = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)

# Save the transparency channel alpha
*_, alpha = cv2.split(src)

gray_layer = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# ... Your image processing

# Duplicate the grayscale image to mimic the BGR image and finally add the transparency
dst = cv2.merge((gray_layer, gray_layer, gray_layer, alpha))
cv2.imwrite("result.png", dst)


Result for grey image:



Grey image with transparency



Result for BGR image:








share|improve this answer


























  • you have example ?

    – lyca
    Nov 19 '18 at 18:16











  • Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

    – Dan Mašek
    Nov 19 '18 at 21:24
















0














You have to add a fourth channel in your array so that the transparency information can be encoded in the alpha channel.



Here is a python code example:



import cv2
file_name = "source.png"

src = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)

# Save the transparency channel alpha
*_, alpha = cv2.split(src)

gray_layer = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# ... Your image processing

# Duplicate the grayscale image to mimic the BGR image and finally add the transparency
dst = cv2.merge((gray_layer, gray_layer, gray_layer, alpha))
cv2.imwrite("result.png", dst)


Result for grey image:



Grey image with transparency



Result for BGR image:








share|improve this answer


























  • you have example ?

    – lyca
    Nov 19 '18 at 18:16











  • Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

    – Dan Mašek
    Nov 19 '18 at 21:24














0












0








0







You have to add a fourth channel in your array so that the transparency information can be encoded in the alpha channel.



Here is a python code example:



import cv2
file_name = "source.png"

src = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)

# Save the transparency channel alpha
*_, alpha = cv2.split(src)

gray_layer = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# ... Your image processing

# Duplicate the grayscale image to mimic the BGR image and finally add the transparency
dst = cv2.merge((gray_layer, gray_layer, gray_layer, alpha))
cv2.imwrite("result.png", dst)


Result for grey image:



Grey image with transparency



Result for BGR image:








share|improve this answer















You have to add a fourth channel in your array so that the transparency information can be encoded in the alpha channel.



Here is a python code example:



import cv2
file_name = "source.png"

src = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)

# Save the transparency channel alpha
*_, alpha = cv2.split(src)

gray_layer = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# ... Your image processing

# Duplicate the grayscale image to mimic the BGR image and finally add the transparency
dst = cv2.merge((gray_layer, gray_layer, gray_layer, alpha))
cv2.imwrite("result.png", dst)


Result for grey image:



Grey image with transparency



Result for BGR image:









share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 19 '18 at 22:02

























answered Nov 19 '18 at 18:07









leoburgyleoburgy

1107




1107













  • you have example ?

    – lyca
    Nov 19 '18 at 18:16











  • Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

    – Dan Mašek
    Nov 19 '18 at 21:24



















  • you have example ?

    – lyca
    Nov 19 '18 at 18:16











  • Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

    – Dan Mašek
    Nov 19 '18 at 21:24

















you have example ?

– lyca
Nov 19 '18 at 18:16





you have example ?

– lyca
Nov 19 '18 at 18:16













Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

– Dan Mašek
Nov 19 '18 at 21:24





Please, don't use magic numbers in code samples. That 1 in cv2.imread should really be a cv2.IMREAD_COLOR. | However, looking at this again, it seems much of this is unnecessary. OP's input image already contains a transparency channel, so there's no need to determine it again using threshold.

– Dan Mašek
Nov 19 '18 at 21:24


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53380318%2fproblem-about-background-transparent-png-format-opencv-with-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?