import cv2 import numpy as np def cleanImageBackground(image_name, ksize, option=1): ''' Ref: stackoverflow.com/../what-processing-steps-should-i-use-to-clean-photos-of -line-drawings ''' img = cv2.imread(image_name) img_blur = cv2.blur(img, (8, 8)) img_white = cv2.dilate(img_blur, np.ones((ksize, ksize), np.uint8)) img_gray = cv2.imread(image_name, 0) ht, wd, ch = img.shape for y in range(0, ht): for x in range(0, wd): if(option == 1): img_gray[y, x] = min(255, max(255 * int(img[y, x, 0]) / int(img_white[y, x, 0]), 255 * int(img[y, x, 1]) / int(img_white[y, x, 1]), 255 * int(img[y, x, 2]) / int(img_white[y, x, 2]) ) ) else: img_gray[y, x] = min(255, max(255 + int(img[y, x, 0]) - int(img_white[y, x, 0]), 255 + int(img[y, x, 1]) - int(img_white[y, x, 1]), 255 + int(img[y, x, 2]) - int(img_white[y, x, 2]) ) ) return img_gray ret, img_thresh = cv2.threshold(cleanImageBackground('imgCleanBg.png', 15, 2), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) cv2.imwrite('imgCleanedBg.png', img_thresh)