gpt4 book ai didi

opencv - 图像倾斜 - 无法使用 CV2 检测水平线

转载 作者:行者123 更新时间:2023-12-02 16:51:25 25 4
gpt4 key购买 nike

在这张图片中,我试图检测水平线。当图像不倾斜时,该代码运行良好。然而,它不适用于这种倾斜的图像。我尝试过这种方法通过直方图检测直角,但很多时候实际上使它更加倾斜 - python-opencv-skew-correction-for-ocr

Skewed image

下面是检测水平线的代码:

    gray=cv2.cvtColor(img_final_bin,cv2.COLOR_BGR2GRAY)
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (100,1))
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts, hierarchy = cv2.findContours(detected_lines, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


boundingBoxes = [list(cv2.boundingRect(c)) for c in cnts]

下面是倾斜校正的代码,它给了我错误的结果:

def correct_skew(image, delta=0.001, limit=3):
def determine_score(arr, angle):
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]

print("thresh", thresh.shape)
thresh1 = thresh[0:500, 0:500]
print("thresh1", thresh1.shape)

scores = []
angles = np.arange(-limit, limit + delta, delta)
for i, angle in enumerate(angles):
histogram, score = determine_score(thresh1, angle)
scores.append(score)
# if i%100 == 0:
# print(score, angle, len(angles), i)

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, \
borderMode=cv2.BORDER_REPLICATE)

return best_angle, rotated

最佳答案

基于ImageMagick的Python Wand具有纠偏功能。

输入:

enter image description here


from wand.image import Image
from wand.display import display

with Image(filename='table.png') as img:
img.deskew(0.4*img.quantum_range)
img.save(filename='table_deskew.png')
display(img)


结果:

enter image description here

关于opencv - 图像倾斜 - 无法使用 CV2 检测水平线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61442184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com