Last active
December 12, 2021 02:42
-
-
Save hanglearning/f1d6ca611357fefd52a3db227b1342fa to your computer and use it in GitHub Desktop.
Crop white space around figure
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
# references | |
# https://www.programmersought.com/article/8966116355/ | |
# https://stackoverflow.com/questions/59758904/check-if-image-is-all-white-pixels-with-opencv | |
# figures in this paper were all cropped using this code snippet - https://arxiv.org/pdf/2101.03300.pdf | |
# usage - save this code snippet as a python file and use two arguments | |
# $ python this_program.py </path/to/original/figure> </path/to/output/directory> | |
# example | |
# $ python this_program.py /Users/foo/bar/figures/the_figure.png /Users/foo/bar/cropped_figures | |
# NOTE | |
# 1. need $ pip install opencv-python | |
# 2. there is no ending slash / in </path/to/output/directory> !! | |
# 3. program may take a while to run | |
import cv2 as io | |
import sys | |
import numpy as np | |
im = io.imread(sys.argv[1]) | |
def corp_margin(img): | |
img2=img.sum(axis=2) | |
(row,col)=img2.shape | |
for r in range(0,row): | |
if np.mean(img2[r]) != 765: | |
row_top=r | |
break | |
for r in range(row-1,0,-1): | |
if np.mean(img2[r]) != 765: | |
raw_down=r | |
break | |
# if want to save bottom padding, uncomment the following line | |
# raw_down = row - 1 | |
for c in range(0,col): | |
if img2.sum(axis=0)[c]/row != 765: | |
col_top=c | |
break | |
for c in range(col-1,0,-1): | |
if img2.sum(axis=0)[c]/row != 765: | |
col_down=c | |
break | |
new_img=img[row_top:raw_down+1,col_top:col_down+1,0:3] | |
return new_img | |
img_re = corp_margin(im) | |
io.imwrite(f"{sys.argv[2]}/{sys.argv[1].split('/')[-1]}",img_re) | |
# io.imshow(img_re) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment