在 OpenCV(或 skimage)中使用 Projection Profile Deskew 方法后,将旋转图像的背景更改为白色而不是黑色
Change the background of rotated image to White instead of black after using Projection Profile Deskew method in OpenCV (or skimage)
我在我的二进制图像上使用了 Projection Profile
方法来获得去歪斜版本。一切都很好,但旋转后的图像有黑色区域,其中应用了歪斜校正。 如何将该区域转换为白色而不是黑色。下面是投影配置文件的代码。
def correct_skew(image, delta=1, limit=5):
"""
image : input
delta : sampling in the -limit,limit + delta range
limit : range of angles to explore
"""
# Function that returns the score of histogram for the given angle at which we check
def determine_score(arr, angle):
"""
arr : binarized image
angle : angle at which we calcuate the score
"""
data = inter.rotate(arr, angle, reshape=False, order=0)
histogram = np.sum(data, axis=1)
score = np.sum((histogram[1:] - histogram[:-1]) ** 2)
return histogram, score
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
scores = []
angles = np.arange(-limit, limit + delta, delta)
for angle in angles:
histogram, score = determine_score(thresh, angle)
scores.append(score)
best_angle = angles[scores.index(max(scores))]
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, best_angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC)
return best_angle, rotated
这是校正后的图像:
原始二进制图像:
cv2.warpaffine 文档指出该函数采用可选参数,即 borderValue
。默认情况下,此值为 (0, 0, 0)
,您可以通过调用 warpaffine 例程来更改此值:
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode = cv2.BORDER_CONSTANT, borderValue=np.array([255, 255, 255]))
我在我的二进制图像上使用了 Projection Profile
方法来获得去歪斜版本。一切都很好,但旋转后的图像有黑色区域,其中应用了歪斜校正。 如何将该区域转换为白色而不是黑色。下面是投影配置文件的代码。
def correct_skew(image, delta=1, limit=5):
"""
image : input
delta : sampling in the -limit,limit + delta range
limit : range of angles to explore
"""
# Function that returns the score of histogram for the given angle at which we check
def determine_score(arr, angle):
"""
arr : binarized image
angle : angle at which we calcuate the score
"""
data = inter.rotate(arr, angle, reshape=False, order=0)
histogram = np.sum(data, axis=1)
score = np.sum((histogram[1:] - histogram[:-1]) ** 2)
return histogram, score
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
scores = []
angles = np.arange(-limit, limit + delta, delta)
for angle in angles:
histogram, score = determine_score(thresh, angle)
scores.append(score)
best_angle = angles[scores.index(max(scores))]
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, best_angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC)
return best_angle, rotated
这是校正后的图像:
原始二进制图像:
cv2.warpaffine 文档指出该函数采用可选参数,即 borderValue
。默认情况下,此值为 (0, 0, 0)
,您可以通过调用 warpaffine 例程来更改此值:
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode = cv2.BORDER_CONSTANT, borderValue=np.array([255, 255, 255]))