Created
February 21, 2023 05:32
-
-
Save SuddenDevelopment/24866aefb467c4bfc2a932e65a3a3b9f to your computer and use it in GitHub Desktop.
add a grayscale gaussian blur to an image and set the blacks to transparent, converting from jpg to png
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| import cv2 | |
| import os | |
| # install all the above packages with pip3 | |
| # run this by setting the directories and calling fro command line | |
| # python3 processImages.py | |
| IMAGEFOLDER = '/Users/anthonyaragues/Downloads/in/' | |
| OUTPUTFOLDER = '/Users/anthonyaragues/Downloads/out/' | |
| def noisy(image, sigma=0.005): | |
| row, col, ch = image.shape | |
| gauss = sigma * np.random.randn(row, col, ch) | |
| gauss = gauss.reshape(row, col, ch) | |
| noisy = image + image * gauss | |
| return noisy | |
| def turnGray(image): | |
| # Convert the image to grayscale | |
| gray = cv2.cvtColor(np.uint8(image), cv2.COLOR_RGBA2GRAY) | |
| # Convert the grayscale image back to RGBA format using the alpha channel from the original image | |
| rgba = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGBA) | |
| # Copy the alpha channel from the original image to the grayscale image | |
| rgba[:, :, 3] = image[:, :, 3] | |
| return rgba | |
| def convertImage(strFile, strOut): | |
| img = cv2.imread(strFile) | |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| # Create a mask of the image where black pixels are transparent | |
| mask = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY_INV)[1] | |
| # Invert the mask so that black pixels are transparent | |
| mask = cv2.bitwise_not(mask) | |
| # Create a 4-channel image with transparency | |
| rgba = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA) | |
| rgba = noisy(rgba) | |
| # Set the alpha channel of the image using the mask | |
| rgba[:, :, 3] = mask | |
| rgba = turnGray(rgba) | |
| cv2.imwrite(strOut, rgba) | |
| for strFile in [file for file in os.listdir(IMAGEFOLDER)]: | |
| if '.jpg' in strFile: | |
| strOut = strFile.replace('.jpg', '.png') | |
| convertImage(f'{IMAGEFOLDER}{strFile}', f'{OUTPUTFOLDER}{strOut}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment