import cv2 import numpy as np import imghdr import os def removeBackground ( file , savePath ) : try : img = cv2 . imread ( file ) gray = cv2 . cvtColor ( img , cv2 . COLOR_BGR2GRAY ) mask = cv2 . threshold ( gray , 250 , 255 , cv2 . THRESH_BINARY ) [ 1 ] mask = 255 - mask kernel = np . ones ( ( 3 , 3 ) , np . uint8 ) mask = cv2 . morphologyEx ( mask , cv2 . MORPH_OPEN , kernel ) mask = cv2 . morphologyEx ( mask , cv2 . MORPH_CLOSE , kernel ) mask = cv2 . GaussianBlur ( mask , ( 0 , 0 ) , sigmaX = 2 , sigmaY = 2 , borderType = cv2 . BORDER_DEFAULT ) mask = ( 2 * ( mask . astype ( np . float32 ) ) - 255.0 ) . clip ( 0 , 255 ) . astype ( np . uint8 ) result = img . copy ( ) result = cv2 . cvtColor ( result , cv2 . COLOR_BGR2BGRA ) result [ : , : , 3 ] = mask cv2 . imwrite ( savePath , result ) cv2 . waitKey ( 0 ) cv2 . destroyAllWindows ( ) except : open ( savePath , 'wb' ) . write ( file ) saveTo = 'noBgImages' for i in range ( 1 , 17500 ) : file = str ( i ) + '.png' if os . path . isfile ( file ) : if imghdr . what ( file ) == 'png' or imghdr . what ( file ) == 'jpeg' : print ( f'{i}: Removing bg from{file}, saving to{saveTo}\\{file}' ) removeBackground ( file , saveTo + '\\' + file ) else : print ( f'{i}[SKIP] NOT A PNG ({imghdr.what(file)}).{file}' )