Skip to content

Instantly share code, notes, and snippets.

@Iunius118
Last active January 8, 2022 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Iunius118/2dbee063bbceef91a77c46d1859212ca to your computer and use it in GitHub Desktop.
Save Iunius118/2dbee063bbceef91a77c46d1859212ca to your computer and use it in GitHub Desktop.
Merge alpha channel from an image to another image (OpenCV is required)
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