1

I am trying to replace all black pixels in an image with pixels of another image...

this is the code I have so far-

imgFront = cv2.imread('withoutbackground.jpg')
imgBack = cv2.imread('background.jpg')

height, width = img.shape[:2]

resizeBack = cv2.resize(imgBack, (width, height), interpolation = cv2.INTER_CUBIC)

for i in range(width):
    for j in range(height):
        pixel = imgFront[j, i]
        if pixel == [255, 255, 255]:
            imgFront[j, i] = resizeBack[j, i] 

however I am getting an error message that says incorrect syntax on this part --

pixel = imgFront[j, i]

which is weird because I am looking right at the opencv documentation and thats how it says to do it..

Bahrom
  • 4,752
  • 32
  • 41
GarudaAiacos
  • 161
  • 2
  • 17

2 Answers2

1

Your idea is correct, but there are some minor mistakes.

First, in line 3, it should be the shape of imgFront right?:

height, width = imgFront.shape[:2]

Second, in line if pixel == [255, 255, 255]: you should change it to :

np.all(pixel == [0, 0, 0])

as black color should be (0,0,0)

All in all, the following code works fine for me:

import cv2
import numpy as np

imgFront = cv2.imread('withoutbackground.jpg')
imgBack = cv2.imread('background.jpg')

height, width = imgFront.shape[:2]

resizeBack = cv2.resize(imgBack, (width, height), interpolation = cv2.INTER_CUBIC)

for i in range(width):
    for j in range(height):
        pixel = imgFront[j, i]
        if np.all(pixel == [0, 0, 0]):
            imgFront[j, i] = resizeBack[j, i] 
VICTOR
  • 1,894
  • 5
  • 25
  • 54
-2

I don't believe it is possible to make a .jpg background transparent (see post: Transparent background in JPEG image.

You can try PNG or GIF instead.

Community
  • 1
  • 1
  • I dont think he wants to make it transparent but change with another image – VICTOR Jul 04 '16 at 07:51
  • His original code showed that he set the background pixels to transparent, and then saved the output to a JPEG, and then he asks why the background is black. – Elizabeth Chu Jul 05 '16 at 16:18