# How do transparent background of png image in opencv?

**URL:** <https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879>\
**Category:** Uncategorized\
**Tags:** imgproc\
**Created:** [October 27, 2021, 9:59am UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879 "2021-10-27T09:59:25Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![payam\_mohammadi](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/payam_mohammadi/32/3335_2.png) [@payam\_mohammadi](https://forum.opencv.org/u/payam_mohammadi)\
**Post date:** [October 27, 2021, 9:59am UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/1 "2021-10-27T09:59:25Z")

</div>

hello  
i have an png image  
but when i use it in on a opencv window  
it can not transparent background

please help to solve it  
i want in png image only show lines (not background)

```auto
import cv2
import numpy as np
  
img1 = cv2.imread('c:/51.jpg')
ball = cv2.imread('c:/pit.png')

RED= [0,0,255]
constant= cv2.copyMakeBorder(ball,5,5,5,5,cv2.BORDER_CONSTANT,value=RED)

img1[20:219, 30:335] = constant

cv2.imshow('HORI8TAL', img1)

  
cv2.waitKey(0)
cv2.destroyAllWindows()

```

 ![3434](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/e/e375c891cbf256841cabce1f731ecde383b67ab1.jpeg)

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [October 27, 2021, 5:40pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/2 "2021-10-27T17:40:05Z")

</div>

> <https://github.com/opencv/opencv/issues/20780>
>
> This is a feature request for the \`imgproc\` module.
> 
> Motivation: frequently, p…eople (on Stack Overflow and elsewhere) want to overlay one image onto another, with an actual alpha channel. That means it's not just blending two pictures, or fading two pictures with one global alpha value. The top image is frequently not of the same size as the bottom one, and a particular position is desired.
> 
> Such a function would:
> \- take a destination image
> \- take an overlay image that should have an alpha-channel (but need not)
> \- take a position
> \- if the destination image is an empty Mat, resize it to overlay size, and generate the stereotypical gray checkerboard background instead
> \- overlay the top image at the given position (the overlay may be completely or partially off-screen)
> \- be sensitive to the alpha channel of the \*bottom\* image, and update it
> \- use the alpha channel of the top and bottom image to blend each pixel accordingly
> \- optionally erase color data that is completely transparent (GIMP doesn't do it...)
> \- the \`dst\` image could be altered or left alone, that's a design decision
> 
> \[Related but separate concepts\](https://github.com/opencv/opencv/issues?q=is%3Aissue+label%3A%22category%3A+imgproc%22++%28blend+OR+alpha+OR+transparen%29):
> \- \`cvtColor\` with \`BGRA2BGR\`, which simply drops the fourth channel
> \- drawing of primitives (lines and shapes) with some transparency
> \- blend modes, which only take into account the color channels of two images (in the basic formulation)
> \- simple fading, which applies the same transparency to every overlying pixel
> \- taking a subregion of a Mat and copying data into it
> 
> I think this would be a popular function to have. It could do more or less of the described functionality.
> 
> Until now, the described functionality required someone to take an explicit subregion, split the channels of the \`Mat\`s, and calculate the result manually (using whole-array operations).
> 
> Here is some... \*pseudocode\* that should be a good guideline for a C++ implementation. Ask me if any of that Python is unfamiliar to you. I chose to work with floats because that makes the numerics slightly simpler. This code should be able to handle \`uint8\` and \`float32\` without problems.
> 
> Another "defect": this assumes a linear color space. That is often \*not\* the case but all of OpenCV assumes it. Accounting for the gamma-mapping would be "more" correct.
> 
> \`\`\`python
> \#!/usr/bin/env python3
> 
> import os
> import sys
> import time
> import numpy as np
> import cv2 as cv
> 
> np.set\_printoptions(suppress=True, linewidth=120)
> 
> def intersect\_rects(r1, r2):
> (r1x, r1y, r1w, r1h) = r1
> (r2x, r2y, r2w, r2h) = r2
> 
> rx = max(r1x, r2x)
> rw = min(r1x+r1w, r2x+r2w) - rx
> 
> ry = max(r1y, r2y)
> rh = min(r1y+r1h, r2y+r2h) - ry
> 
> if rw \> 0 and rh \> 0:
> return np.array(\[rx, ry, rw, rh\])
> else:
> return None
> 
> def rect\_to\_slice(rect):
> (rx, ry, rw, rh) = rect
> return np.s\_\[ry:ry+rh, rx:rx+rw\]
> 
> def composite(src, dst=None, position=(0,0), background\_color=None):
> # this is pronounced "com-PUH-sit" to all you non-native speakers
> 
> (src\_height, src\_width, src\_ch) = src.shape
> src\_has\_alpha = (src\_ch == 4)
> 
> # shortcut
> # composite() may be useful to use in imshow, so people "see" transparent data
> # and if data has no alpha channel, pass through
> if dst is None and not src\_has\_alpha:
> return src
> 
> if dst is None:
> # background (grid or flat color)
> dst = np.empty((src\_height, src\_width, 3), dtype=np.uint8)
> if background\_color is None:
> (i,j) = np.mgrid\[0:src\_height, 0:src\_width\]
> i = (i // 8) % 2
> j = (j // 8) % 2
> dst\[i == j\] = 192
> dst\[i != j\] = 255
> else:
> dst\[:,:\] = background\_color
> 
> (dst\_height, dst\_width) = dst.shape\[:2\]
> dst\_has\_alpha = (dst.shape\[2\] == 4)
> 
> src\_rect = np.array(\[0, 0, src\_width, src\_height\])
> dst\_rect = np.array(\[0, 0, dst\_width, dst\_height\])
> offset = position + (0,0) # 4-tuple
> 
> src\_roi = intersect\_rects(src\_rect, dst\_rect - offset)
> dst\_roi = intersect\_rects(dst\_rect, src\_rect + offset)
> 
> if src\_roi is not None: # there is overlap
> assert dst\_roi is not None
> dst\_slice = dst\[rect\_to\_slice(dst\_roi)\]
> src\_slice = src\[rect\_to\_slice(src\_roi)\]
> 
> if src\_has\_alpha:
> src\_alpha = src\_slice\[:,:,3\]\[..., None\] # None adds a dimension for numpy broadcast rules
> if src\_alpha.dtype == np.uint8:
> src\_alpha = src\_alpha / np.float32(255)
> 
> blended = src\_slice\[:,:,0:3\] \* src\_alpha + dst\_slice\[:,:,0:3\] \* (1-src\_alpha)
> 
> else:
> blended = src\_slice\[:,:,0:3\]
> 
> dst\_slice\[:,:,0:3\] = blended.astype(dst.dtype)
> 
> if dst\_has\_alpha:
> new\_alpha = src\_slice\[:,:,3\] + dst\_slice\[:,:,3\] \* (1-src\_alpha)
> dst\_slice\[:,:,3\] = new\_alpha.astype(dst.dtype)
> 
> return dst
> 
> def main():
> logo = cv.imread(cv.samples.findFile("opencv-logo.png"), cv.IMREAD\_UNCHANGED)
> lena = cv.imread(cv.samples.findFile("lena.jpg"), cv.IMREAD\_UNCHANGED)
> 
> # smaller logo...
> # inpainting here to fill ordinarily transparent areas with color
> # those transparent pixels will become part of edge pixels (where alpha channel has gradients)
> # and if they stay black, those edge pixels will turn dark
> # a different fix would require alpha-aware resizing
> logo\[:,:,0:3\] = cv.inpaint(logo\[:,:,0:3\], inpaintMask=255-logo\[:,:,3\], inpaintRadius=0, flags=cv.INPAINT\_NS)
> logo = cv.pyrDown(logo)
> 
> composite0 = composite(logo)
> composite1 = composite(logo, background\_color=(128, 255, 255))
> composite2 = composite(logo, dst=lena.copy(), position=(257,59))
> # NOTE: \`dst\` will be altered
> # this is a useful behavior in case we want to composite multiple things onto the same background
> # it's like the drawing primitives in imgproc
> # if you don't want it to be touched, pass a copy instead (as is done here)
> 
> logo = (cv.pyrDown(cv.pyrDown(logo)))
> logo\[:,:,3\] //= 2 # reduce transparency to half strength for this demo
> for k in range(100):
> x = np.random.randint(-100, +600)
> y = np.random.randint(-100, +600)
> composite(logo, dst=lena, position=(x,y))
> 
> cv.imshow("composite0", composite0)
> cv.imshow("composite1", composite1)
> cv.imshow("composite2", composite2)
> cv.imshow("lena", lena)
> 
> while True:
> key = cv.waitKey(-1)
> if key in (13, 27): # ESC, ENTER
> break
> 
> cv.destroyAllWindows()
> 
> if \_\_name\_\_ == '\_\_main\_\_':
> main()
> \`\`\`
> 
> !\[composite0\](https://user-images.githubusercontent.com/7065108/135487541-4979e1f5-5f85-4384-8cfb-c750d7b23837.png) !\[composite1\](https://user-images.githubusercontent.com/7065108/135487524-1bf7122d-ef50-4eb5-bf64-8a39f07dba11.png)
> 
> !\[composite2\](https://user-images.githubusercontent.com/7065108/135487497-a17b1b18-541f-452b-a9e6-40cbd6caebb9.png)
> 
> !\[lena\](https://user-images.githubusercontent.com/7065108/135488615-9a856a1e-a9ee-4bef-83f6-81d49235565b.png)

---

<div class="post-metadata">

**Author:** ![sturkmen](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/sturkmen/32/13_2.png) [@sturkmen](https://forum.opencv.org/u/sturkmen)\
**Post date:** [October 27, 2021, 5:44pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/3 "2021-10-27T17:44:59Z")

</div>

could you upload here your images (51.jpg , pit.png)

---

<div class="post-metadata">

**Author:** ![payam\_mohammadi](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/payam_mohammadi/32/3335_2.png) [@payam\_mohammadi](https://forum.opencv.org/u/payam_mohammadi)\
**Post date:** [October 28, 2021, 8:42am UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/4 "2021-10-28T08:42:07Z")

</div>

![562-5624191_soccer-net-clip-art](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/6/694d1251dba0646412856b2e4081919efbc7845b.png)  
 ![51](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/1/13fcaadff22fff3ee71bdd8097d7361eb8b9819a.jpeg)  
thanks just rename files

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [October 28, 2021, 8:48am UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/5 "2021-10-28T08:48:30Z")

</div>

untried idea:

invert your lines image (so the lines are white) and use it as a mask with `copyTo()`

---

<div class="post-metadata">

**Author:** ![sturkmen](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/sturkmen/32/13_2.png) [@sturkmen](https://forum.opencv.org/u/sturkmen)\
**Post date:** [October 28, 2021, 10:06pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/6 "2021-10-28T22:06:05Z")

</div>

a naive idea could be drawing found contours which produces like  
 ![HORI8TAL](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/2/26df393a12d6301b9a0da91a4266614f68acd29a.jpeg)

```auto
import cv2
import numpy as np
  
img1 = cv2.imread('d:/test/51.jpeg')
ball = cv2.imread('d:/test/pit.png',cv2.IMREAD_REDUCED_GRAYSCALE_2)

contours, hierarchy = cv2.findContours( ball, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours( img1, contours, -1, (0,0,255),2, cv2.LINE_AA, None, 99, (20,30))
cv2.imshow('HORI8TAL', img1)
cv2.waitKey(0)
  
cv2.destroyAllWindows()

```

( pit.png i changed it using your image’s alpha channel and saves as grayscale)  
 ![pit](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/e/e91257ea4f2d919285a2fed26ce858ce6cfc1722.png)

---

<div class="post-metadata">

**Author:** ![sturkmen](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/sturkmen/32/13_2.png) [@sturkmen](https://forum.opencv.org/u/sturkmen)\
**Post date:** [October 28, 2021, 10:08pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/7 "2021-10-28T22:08:20Z")

</div>

i don’t know if we can use `copyTo()` in python

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [October 29, 2021, 6:32am UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/8 "2021-10-29T06:32:39Z")

</div>

yes, we can :}

```auto
>>> help(cv2.copyTo)
Help on built-in function copyTo:

copyTo(...)
    copyTo(src, mask[, dst]) -> dst
    . @brief This is an overloaded member function, provided for convenience (python)
    . Copies the matrix to another one.
    . When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.
    . @param src source matrix.
    . @param dst Destination matrix. If it does not have a proper size or type before the operation, it is
    . reallocated.
    . @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
    . elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.

```

---

<div class="post-metadata">

**Author:** ![payam\_mohammadi](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/payam_mohammadi/32/3335_2.png) [@payam\_mohammadi](https://forum.opencv.org/u/payam_mohammadi)\
**Post date:** [October 29, 2021, 1:02pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/9 "2021-10-29T13:02:10Z")

</div>

thank you very much , your helps were great

---

<div class="post-metadata">

**Author:** ![payam\_mohammadi](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/payam_mohammadi/32/3335_2.png) [@payam\_mohammadi](https://forum.opencv.org/u/payam_mohammadi)\
**Post date:** [October 29, 2021, 1:06pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/10 "2021-10-29T13:06:10Z")

</div>

i used draw lines to make pitch , because i couldn’t have click in back of images , thanks again i used your helps in my code

---

<div class="post-metadata">

**Author:** ![payam\_mohammadi](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/payam_mohammadi/32/3335_2.png) [@payam\_mohammadi](https://forum.opencv.org/u/payam_mohammadi)\
**Post date:** [October 29, 2021, 1:12pm UTC](https://forum.opencv.org/t/how-do-transparent-background-of-png-image-in-opencv/5879/11 "2021-10-29T13:12:08Z")

</div>

after change codes i draw this shape only width line and circle

 ![38](https://us1.discourse-cdn.com/flex020/uploads/opencv/original/2X/5/58a6cf3c254042a9e9588a5d66eab5a1a75f8489.jpeg)  
now i can calibrate field by 4 clicks on 4 red circle on the drawn shape and then 4 clicks on real world image as same , then i can use homography for calbration (manually ) , it is very precise , but this is start of my work , i dont know what changes need to do it automatically , (without need to click on real image) , thanks again for your help
