How to remove a black background from an image and make that transparent using opencv?
<p>I am using "PerspectiveTransform" method to transform the image in a given rectangle. Method "warpPerspective" works fine, but the output contains the black background and I want to remove the black color and make that transparent.</p>

<pre><code>import cv2
import numpy as np

img2 = cv2.imread(r"C:\Users\test\Desktop\map.jpg")
input_quad = np.float32([[0,0],[1024,0],[1024,752],[0,752]])
output_quad = np.float32([[4,139],[500,137],[500,650],[159,636]])
lambda_img = np.zeros((728, 992,3), np.uint8)
lambda_img[:,:,:] = 255
lambda_val = cv2.getPerspectiveTransform( input_quad, output_quad )
dst = cv2.warpPerspective(img2,lambda_val,(992,728),lambda_img, cv2.INTER_CUBIC, borderMode=cv2.BORDER_TRANSPARENT)
cv2.imwrite("Valchanged.png",dst)

[enter image description here][1]
[![enter image description here][2]][2]
</code></pre>

<p>Below is the output I have revived. </p>

<p><a href="https://i.stack.imgur.com/9oH53.png" rel="nofollow"><img src="https://i.stack.imgur.com/9oH53.png" alt="enter image description here"></a></p>

<p>As your input image is in <code>.jpg</code> format so you need to convert the input image from <code>BGR</code> domain to <code>BGRA</code> domain:</p>

<pre><code>img2 = cv2.imread(r"C:\Users\test\Desktop\map.jpg")
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2BGRA)
</code></pre>

<p>Also you don't need to define a new <code>lambda_img</code> on your side, <code>cv2.warpPerspective</code> returns a numpy array after applying the transformation. </p>

<pre><code>dst = cv2.warpPerspective(img2, lambda_val, (992,728), flags = cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT, borderValue = [0, 0, 0, 0])
</code></pre>

<p>When you define <code>borderMode=cv2.BORDER_CONSTANT</code>, you also need to define a <code>borderValue</code> which gets filled along the borders, in this case it is black color with 0 alpha value i.e. Transparent or <code>"#00000000"</code></p>

python opencv