opencv+python实现图像矫正

2022-08-01 10:43:16

本文实例为大家分享了opencv+python实现图像矫正的具体代码,供大家参考,具体内容如下需求:将斜着拍摄的文本图像进行矫正python代码importnumpyasnpimportcv2...

本文实例为大家分享了opencv+python实现图像矫正的具体代码,供大家参考,具体内容如下

需求:将斜着拍摄的文本图像进行矫正

python代码

import numpy as np
import cv2 as cv


def shape_correction(img):
  (height, width) = img.shape[:2]
  print(img.shape)

  img_gau = cv.GaussianBlur(img, (5, 5), 0)
  canny = cv.Canny(img_gau, 60, 200)
  # cv.imshow("g-canny", canny)
 
  kernel = cv.getStructuringElement(cv.MORPH_CROSS, (4,3))
 
  dilated = cv.dilate(canny, kernel, iterations=8) 
  # cv.imshow('img_dilated', dilated)

  # 寻找轮廓
  contours, hierarchy = cv.findjsContours(dilated, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
  # print(len(contours), hierarchy, sep='\n')

  # 找到最外层面积最大的轮廓

  area = 0
  # print("area:{}".format(area))

  index = 0
  for i in range(len(contours)):
    x, y, w, h = cv.boundingRect(contours[i])
    # 排除非文本区域
    if w < 35 and h < 35:
      continue
    # 防止矩形区域过大不精准  
    if h > 0.99 * height or w > 0.99 * width:
      continue
    # draw rectangle around contour on original image
    # cv.rectangle(img, (x, y), (x + w, y + h), (255php, 0, 255), 2)
    tmpArea = w * h
    if tmpArea >= area:
      area = tmpArea
      index = i

  # 得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度)
  rect = cv.minAreaRect(contours[index])
  # 画出矩形框
  # box = cv.boxPoints(rect)
  # box = np.int0(box)
  # cv.drawContours(img, [box], 0, (0, 0, 255), 2)

  # cv.imshow('img', img)
  print("rect:{}".format(rect))
  angle = rect[-1]
  # print(angle)

  # 角度大于85度或小于5度不矫正
  if angle > 85 or angle < 5:
    angle = 0
  elif angle < 45:
    angle = angle - 0
  else:
    angle = angle - 90

  M = cv.getRotationMatrix2D(rect[0], angle, 1)
  rotated = cv.warpAffine(img, M, (width, height), flags=cv.INTER_CUBIC, borderValue=(255, 255, 255))
 
  cv.imshow('Rotated', rotated)
  return rotated


src = cv.ijavascriptmread('/res-normal.png', 0)
rotated = shape_correction(src)
cv.waitKey(0)

算法流程

opencv+python实现图像矫正

算法核心思想:

获取图像中的文本区域矩形轮廓,找到其中面积最大的,对其进行最小外接矩形计算,得到最小外接矩形的旋转角度,再根据旋转角度进行仿射变换。

测试效果

opencv+python实现图像矫正

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。