Reputation: 1947
Here is origin image:
Now, I wanna remove the light impact to get image like this:
And, I am trying to get it by the following code:
#!/usr/bin/env python
# coding: utf-8
import cv2
import numpy as np
debug = True
table = np.array([((i / 255.0) ** (1.0/0.3)) * 255 for i in np.arange(0, 256)]).astype("uint8")
def parse(image):
dilated_img = cv2.dilate(image, np.ones((7, 7), np.uint8))
# if debug:
# cv2.imshow('dilated', dilated_img)
# cv2.waitKey(0)
bg_img = cv2.medianBlur(dilated_img, 21)
# if debug:
# cv2.imshow('median blur', bg_img)
# cv2.waitKey(0)
diff_img = 255 - cv2.absdiff(image, bg_img)
if debug:
cv2.imshow('origin vs back diff', diff_img)
cv2.waitKey(0)
norm_img = diff_img.copy()
cv2.normalize(diff_img, diff_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
if debug:
cv2.imshow('first norm', norm_img)
cv2.waitKey(0)
_, thr_img = cv2.threshold(norm_img, 253, 0, cv2.THRESH_TRUNC)
# thr_img = norm_img
cv2.normalize(thr_img, thr_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
thr_img = cv2.LUT(thr_img, table)
if debug:
cv2.imshow('second norm', thr_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
compare = cv2.resize(np.hstack([image, cv2.imread("reult.JPEG", 0), thr_img]), None, fx=0.5, fy=0.5)
cv2.imshow("Analysis", compare)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('./nijie.jpg', thr_img)
if __name__ == '__main__':
parse(cv2.imread("original.JPG", 0))
I got image like this:
Seems almost done, but the middle is a little dark, and the top right line is not so clear.
Is there any way to make it better?
Env:
Python: 3.6.5
Opencv: 3.4.0
Any suggestion for this is appreciated.
Thanks.
Upvotes: 3
Views: 2012
Reputation: 53091
You can improve your image by using adaptive thresholding in Python/OpenCV.
Input:
import cv2
# read image
img = cv2.imread("kanji.jpg")
# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# do adaptive threshold on gray image
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 51, 25)
# write results to disk
cv2.imwrite("kanji_threshold.jpg", thresh)
# display it
cv2.imshow("THRESHOLD", thresh)
cv2.waitKey(0)
Threshold:
Upvotes: 1