Last active
January 8, 2022 10:55
-
-
Save Iunius118/2dbee063bbceef91a77c46d1859212ca to your computer and use it in GitHub Desktop.
Merge alpha channel from an image to another image (OpenCV is required)
This file contains 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 argparse | |
import cv2 | |
def main(): | |
args = parse_args() | |
alpha, img = read_images(args) | |
new_img = marge_alpha(args, alpha, img) | |
write_image(args, new_img) | |
def parse_args(): | |
parser = argparse.ArgumentParser(description='Merge alpha channel from an image to another image') | |
parser.add_argument('aipha_image_path', help='Path to image to extract the alpha channel') | |
parser.add_argument('color_image_path', help='Path to image to extract the color channels (r, g, b)') | |
parser.add_argument('-o', '--output', help='Path to write the result image. If it is omitted, the result will overwrite the image in color_image_path') | |
parser.add_argument('-g', '--gray', action='store_true', help='Force gray-scale to be used as alpha') | |
return parser.parse_args() | |
def read_images(args): | |
alpha = cv2.imread(args.aipha_image_path, cv2.IMREAD_UNCHANGED) | |
img = cv2.imread(args.color_image_path) | |
return alpha, img | |
def marge_alpha(args, alpha, img): | |
b, g, r = cv2.split(img) | |
if alpha.shape[2] < 4 or args.gray: | |
# Use gray-scale as alpha | |
gray = cv2.cvtColor(alpha, cv2.COLOR_BGR2GRAY) | |
new_img = cv2.merge((b, g, r, gray)) | |
else: | |
_, _, _, a = cv2.split(alpha) | |
new_img = cv2.merge((b, g, r, a)) | |
return new_img | |
def write_image(args, img): | |
if args.output is not None: | |
cv2.imwrite(args.output, img) | |
else: | |
# Overwrite color image file | |
cv2.imwrite(args.color_image_path, img) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment