【问题标题】:straightening contoured rectangles in opencv python在opencv python中拉直轮廓矩形
【发布时间】:2017-03-18 20:51:03
【问题描述】:

我有这些 IC 图像,我必须对其进行一些图像处理。我能够找到这些图像的轮廓。但有时这些 IC 会随机旋转。如何将它们拉直为适当的常规矩形?

这些是我的一些轮廓检测图像:

如果有人可以让我开始了解如何将这些图像旋转回直矩形/正方形,我会很高兴。在此先感谢:)

【问题讨论】:

  • 提示:minAreaRect 在轮廓上,然后是rotate。搜索一下,有很多关于如何使用这些功能的示例,无论是在 SO 上还是在一般的网络上。
  • 您可以标记为已解决吗?

标签: python-2.7 opencv image-rotation opencv-contour


【解决方案1】:

这里是解决你问题的代码:

import cv2
import numpy as np

# get the minimum bounding box for the chip image
image = cv2.imread("./chip1.png", cv2.IMREAD_COLOR)
image = image[10:-10,10:-10]
imgray = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)[...,0]
ret, thresh = cv2.threshold(imgray, 20, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
mask = 255 - thresh
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

maxArea = 0
best = None
for contour in contours:
  area = cv2.contourArea(contour)
  if area > maxArea :
    maxArea = area
    best = contour

rect = cv2.minAreaRect(best)
box = cv2.boxPoints(rect)
box = np.int0(box)

#crop image inside bounding box
scale = 1  # cropping margin, 1 == no margin
W = rect[1][0]
H = rect[1][1]

Xs = [i[0] for i in box]
Ys = [i[1] for i in box]
x1 = min(Xs)
x2 = max(Xs)
y1 = min(Ys)
y2 = max(Ys)

angle = rect[2]
rotated = False
if angle < -45:
    angle += 90
    rotated = True

center = (int((x1+x2)/2), int((y1+y2)/2))
size = (int(scale*(x2-x1)), int(scale*(y2-y1)))

M = cv2.getRotationMatrix2D((size[0]/2, size[1]/2), angle, 1.0)

cropped = cv2.getRectSubPix(image, size, center)
cropped = cv2.warpAffine(cropped, M, size)

croppedW = W if not rotated else H
croppedH = H if not rotated else W

image = cv2.getRectSubPix(
    cropped, (int(croppedW*scale), int(croppedH*scale)), (size[0]/2, size[1]/2))

# show result
while True:
  cv2.imshow("result", image)
  k = cv2.waitKey(30) & 0xff
  if k == 27:
      break

这里是结果图像:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2013-05-08
    • 2021-11-19
    • 2017-03-05
    • 2018-03-13
    相关资源
    最近更新 更多