在开始之前,我知道您正在寻求 OpenCV C++ 中该算法的实现,但我的算法需要 FFT 和numpy / scipy
软件包对此非常棒。因此,我将为您提供 OpenCV 中该算法的实现使用Python反而。该代码实际上与 C++ API 非常相似,您可以轻松地对其进行转录。这样,它可以最大限度地减少我学习(或者更确切地说是重新学习......)API 所需的时间,我宁愿向您提供算法以及我执行此任务所执行的步骤,以免浪费任何时间。
因此,我将向您概述我将要做什么。然后我将向您展示使用的 Python 代码numpy, scipy
和 OpenCV 包。作为对使用 MATLAB 的人的奖励,我将向您展示 MATLAB 等效项,并附带 MATLAB 代码!
你能做的就是尝试使用同态过滤 http://en.wikipedia.org/wiki/Homomorphic_filtering。基本上,我们可以用照明和反射率的乘积来表示图像。假设照明是缓慢变化的并且是动态范围的主要贡献者。这本质上是低频内容。反射率代表物体的细节,并假设变化很快。这也是局部对比度的主要贡献者,本质上是高频内容。
该图像可以表示为product这两个。同态过滤尝试并拆分这些组件,然后我们单独过滤它们。完成后,我们将结果合并在一起。由于这是一个乘法模型,因此通常使用log运算,以便我们可以将乘积表示为两项之和。这两项被单独过滤,缩放以强调或弱化它们对图像的贡献,求和,然后取反对数。
阴影是由照明引起的,所以我们能做的就是减少这种阴影对图像的贡献。我们还可以提高反射率,这样我们就可以获得更好的边缘,因为边缘与高频信息相关。
我们通常使用低通滤波器过滤照明,而使用高通滤波器过滤反射率。在本例中,我将选择 sigma 为 10 的高斯核作为低通滤波器。高通滤波器可以通过以下方式获得1
并用低通滤波器进行减法。我将图像变换到对数域,然后使用低通和高通滤波器在频域中对图像进行滤波。然后,我缩放低通和高通结果,将这些分量加回去,然后取反对数。该图像现在更适合进行阈值处理,因为图像变化较小。
我所做的额外后处理是对图像进行阈值处理。这些字母比整体背景更暗,因此任何低于特定阈值的像素都将被归类为文本。我选择的阈值是强度 65。之后,我还清除了接触边界的所有像素,然后删除图像中总面积小于 160 (MATLAB) 或 120 (Python) 像素的任何区域。我还裁剪了图像的一些列,因为我们的分析不需要它们。
以下是一些注意事项:
注意事项 #1 - 消除边界
删除接触边框的任何像素是not内置于 OpenCV 中。然而,MATLAB 有一个等效的函数,称为imclearborder http://www.mathworks.com/help/images/ref/imclearborder.html。我将在 MATLAB 代码中使用它,但对于 OpenCV,这是以下算法:
- 找到图像中的所有轮廓
- 对于图像中的每个轮廓,检查是否有任何轮廓像素位于图像的边界内
- 如果有,请标记该轮廓以进行删除
- 对于我们想要删除的每个轮廓,只需将整个轮廓绘制为黑色
我创建了一个名为imclearborder(imgBW, radius)
在我的代码中,其中radius
是您想要清除边框内的像素数。
注意事项 #2 - 删除特定区域以下的像素区域
删除小于一定数量的任何区域也是如此not在 OpenCV 中实现。在 MATLAB 中,可以方便地使用bwareaopen http://www.mathworks.com/help/images/ref/bwareaopen.html。其基本算法是:
- 找到图像中的所有轮廓
- 如果要填充内部,请分析每个轮廓的区域填充了多少
- 任何小于一定数量的区域,通过用黑色填充内部来清除该轮廓
我创建了一个名为bwareaopen(imgBW)
这对我们来说是这样的。
注意事项 #3 - 用于移除像素区域的区域参数
对于 Python 代码,我必须尝试使用此参数,最终选择了 120。MATLAB 使用了 160。对于 python,120 去掉了一些字符,这是不希望的。我猜我的实现bwareaopen
与 MATLAB 相比是不同的,这可能就是我得到不同结果的原因。
话不多说,这是代码。请注意,我没有使用空间过滤。你可以使用filter2D
在 OpenCV 中,并将该图像与高斯核进行卷积,但我没有这样做,因为使用低通和高通滤波器时的同态滤波传统上是在频域中完成的。您可以使用空间过滤来探索这一点,但您还必须知道size事先准备好你的内核。对于频域滤波,您只需要知道滤波器的标准偏差,这只是与两个参数相比的一个参数。
另外,对于 Python 代码,我将您的图像下载到我的计算机上并运行脚本。对于 MATLAB,您可以在使用图像处理工具箱读取图像时直接引用图像的超链接。
Python代码
import cv2 # For OpenCV modules (For Image I/O and Contour Finding)
import numpy as np # For general purpose array manipulation
import scipy.fftpack # For FFT2
#### imclearborder definition
def imclearborder(imgBW, radius):
# Given a black and white image, first find all of its contours
imgBWcopy = imgBW.copy()
contours,hierarchy = cv2.findContours(imgBWcopy.copy(), cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
# Get dimensions of image
imgRows = imgBW.shape[0]
imgCols = imgBW.shape[1]
contourList = [] # ID list of contours that touch the border
# For each contour...
for idx in np.arange(len(contours)):
# Get the i'th contour
cnt = contours[idx]
# Look at each point in the contour
for pt in cnt:
rowCnt = pt[0][1]
colCnt = pt[0][0]
# If this is within the radius of the border
# this contour goes bye bye!
check1 = (rowCnt >= 0 and rowCnt < radius) or (rowCnt >= imgRows-1-radius and rowCnt < imgRows)
check2 = (colCnt >= 0 and colCnt < radius) or (colCnt >= imgCols-1-radius and colCnt < imgCols)
if check1 or check2:
contourList.append(idx)
break
for idx in contourList:
cv2.drawContours(imgBWcopy, contours, idx, (0,0,0), -1)
return imgBWcopy
#### bwareaopen definition
def bwareaopen(imgBW, areaPixels):
# Given a black and white image, first find all of its contours
imgBWcopy = imgBW.copy()
contours,hierarchy = cv2.findContours(imgBWcopy.copy(), cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
# For each contour, determine its total occupying area
for idx in np.arange(len(contours)):
area = cv2.contourArea(contours[idx])
if (area >= 0 and area <= areaPixels):
cv2.drawContours(imgBWcopy, contours, idx, (0,0,0), -1)
return imgBWcopy
#### Main program
# Read in image
img = cv2.imread('5DnwY.jpg', 0)
# Number of rows and columns
rows = img.shape[0]
cols = img.shape[1]
# Remove some columns from the beginning and end
img = img[:, 59:cols-20]
# Number of rows and columns
rows = img.shape[0]
cols = img.shape[1]
# Convert image to 0 to 1, then do log(1 + I)
imgLog = np.log1p(np.array(img, dtype="float") / 255)
# Create Gaussian mask of sigma = 10
M = 2*rows + 1
N = 2*cols + 1
sigma = 10
(X,Y) = np.meshgrid(np.linspace(0,N-1,N), np.linspace(0,M-1,M))
centerX = np.ceil(N/2)
centerY = np.ceil(M/2)
gaussianNumerator = (X - centerX)**2 + (Y - centerY)**2
# Low pass and high pass filters
Hlow = np.exp(-gaussianNumerator / (2*sigma*sigma))
Hhigh = 1 - Hlow
# Move origin of filters so that it's at the top left corner to
# match with the input image
HlowShift = scipy.fftpack.ifftshift(Hlow.copy())
HhighShift = scipy.fftpack.ifftshift(Hhigh.copy())
# Filter the image and crop
If = scipy.fftpack.fft2(imgLog.copy(), (M,N))
Ioutlow = scipy.real(scipy.fftpack.ifft2(If.copy() * HlowShift, (M,N)))
Iouthigh = scipy.real(scipy.fftpack.ifft2(If.copy() * HhighShift, (M,N)))
# Set scaling factors and add
gamma1 = 0.3
gamma2 = 1.5
Iout = gamma1*Ioutlow[0:rows,0:cols] + gamma2*Iouthigh[0:rows,0:cols]
# Anti-log then rescale to [0,1]
Ihmf = np.expm1(Iout)
Ihmf = (Ihmf - np.min(Ihmf)) / (np.max(Ihmf) - np.min(Ihmf))
Ihmf2 = np.array(255*Ihmf, dtype="uint8")
# Threshold the image - Anything below intensity 65 gets set to white
Ithresh = Ihmf2 < 65
Ithresh = 255*Ithresh.astype("uint8")
# Clear off the border. Choose a border radius of 5 pixels
Iclear = imclearborder(Ithresh, 5)
# Eliminate regions that have areas below 120 pixels
Iopen = bwareaopen(Iclear, 120)
# Show all images
cv2.imshow('Original Image', img)
cv2.imshow('Homomorphic Filtered Result', Ihmf2)
cv2.imshow('Thresholded Result', Ithresh)
cv2.imshow('Opened Result', Iopen)
cv2.waitKey(0)
cv2.destroyAllWindows()
MATLAB代码
clear all;
close all;
% Read in image
I = imread('https://i.stack.imgur.com/5DnwY.jpg');
% Remove some columns from the beginning and end
I = I(:,60:end-20);
% Cast to double and do log. We add with 1 to avoid log(0) error.
I = im2double(I);
I = log(1 + I);
% Create Gaussian mask in frequency domain
% We must specify our mask to be twice the size of the image to avoid
% aliasing.
M = 2*size(I,1) + 1;
N = 2*size(I,2) + 1;
sigma = 10;
[X, Y] = meshgrid(1:N,1:M);
centerX = ceil(N/2);
centerY = ceil(M/2);
gaussianNumerator = (X - centerX).^2 + (Y - centerY).^2;
% Low pass and high pass filters
Hlow = exp(-gaussianNumerator./(2*sigma.^2));
Hhigh = 1 - Hlow;
% Move origin of filters so that it's at the top left corner to match with
% input image
Hlow = ifftshift(Hlow);
Hhigh = ifftshift(Hhigh);
% Filter the image, and crop
If = fft2(I, M, N);
Ioutlow = real(ifft2(Hlow .* If));
Iouthigh = real(ifft2(Hhigh .* If));
% Set scaling factors then add
gamma1 = 0.3;
gamma2 = 1.5;
Iout = gamma1*Ioutlow(1:size(I,1),1:size(I,2)) + ...
gamma2*Iouthigh(1:size(I,1),1:size(I,2));
% Anti-log then rescale to [0,1]
Ihmf = exp(Iout) - 1;
Ihmf = (Ihmf - min(Ihmf(:))) / (max(Ihmf(:)) - min(Ihmf(:)));
% Threshold the image - Anything below intensity 65 gets set to white
Ithresh = Ihmf < 65/255;
% Remove border pixels
Iclear = imclearborder(Ithresh, 8);
% Eliminate regions that have areas below 160 pixels
Iopen = bwareaopen(Iclear, 160);
% Show all of the results
figure;
subplot(4,1,1);
imshow(I);
title('Original Image');
subplot(4,1,2);
imshow(Ihmf);
title('Homomorphic Filtered Result');
subplot(4,1,3);
imshow(Ithresh);
title('Thresholded Result');
subplot(4,1,4);
imshow(Iopen);
title('Opened Result');
这是我得到的结果:
Python
请注意,我重新排列了窗口,使它们在单列中对齐。
MATLAB