Last active
June 19, 2020 07:17
-
-
Save scientificRat/56e76c1c5ed37f3b77ee8f04ddc73502 to your computer and use it in GitHub Desktop.
png tight cut, cut the png background
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 cv2 | |
import os | |
import sys | |
import numpy as np | |
def tight_cut(path): | |
path = os.path.abspath(path) | |
file_name = os.path.basename(path) | |
dir_name = os.path.dirname(path) | |
img: np.ndarray = cv2.imread(path, cv2.IMREAD_UNCHANGED) | |
alpha: np.ndarray = img[:, :, 3] | |
x, y, w, h = cv2.boundingRect(alpha) | |
mask = alpha.astype(np.bool) | |
mask: np.ndarray = mask[..., np.newaxis] | |
img[:, :, :-1] *= mask | |
img[:, :, :-1] += (~mask).astype(img.dtype) * 255 | |
cv2.imwrite(os.path.join(dir_name, "cut_" + file_name), img[y:y + h, x:x + w]) | |
def main(): | |
for path in sys.argv[1:]: | |
tight_cut(path) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment