python - 如何消除光线对图像的影响
问题描述
这是原始图像:
现在,我想消除光线影响以获得这样的图像:
而且,我正在尝试通过以下代码获取它:
#!/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))
我得到这样的图像:
看起来差不多完成了,但是中间有点暗,右上角的线不是那么清晰。
有没有办法让它变得更好?
环境:
蟒蛇:3.6.5
开放式简历:3.4.0
对此的任何建议表示赞赏。
谢谢。
解决方案
您可以通过在 Python/OpenCV 中使用自适应阈值来改善图像。
输入:
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)
临界点: