简体   繁体   中英

Python & OpenCV - Trying to turn transparent pixels into white nontransparent pixels

I'm relatively new to data processing using OpenCV. For a machine learning project, I'm trying to process images so that all the transparent pixels will be turned into white nontransparent pixels for my GAN to use. However, I keep on getting an error when trying to process it. Here is my code below /

    img = cv2.imread(dirfName, cv2.IMREAD_UNCHANGED) (Note Dirftname is a defined variable)
    for col in img:                        
        for row in img[col]:                
            if(img[col,row] == (0,0,0,0)):                    
                    img[col,row] = (255,255,255,255)

    cv2.imwrite((fCropPath + fNameIndent + fname), new_img)

The error is with the if statement and it states: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Note your syntax in the itterations, row and col are not indexes.

import cv2
import numpy as np

img = cv2.imread(dirfName, cv2.IMREAD_UNCHANGED)
for col in img:
    for row in col:
        if(row.__eq__(0).all()): # This is what you want
                row += 255

cv2.imwrite((fCropPath + fNameIndent + fname), new_img)

row.__eq__(0).all() is equivalent to np.all(row == 0)

Furthermore, it is better practice to vectorize your loops:

import cv2
import numpy as np

img = cv2.imread(dirfName, cv2.IMREAD_UNCHANGED)
ind = np.equal(img, 0).all(axis=2)
img[ind] = np.array([255]*4)

cv2.imwrite((fCropPath + fNameIndent + fname), new_img)

The above code does exactly the same thing but vectorized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM