首页 文章

在opencv python中矫正轮廓矩形

提问于
浏览
1

我有这些IC的图像,我必须在其上进行一些图像处理 . 我能够找到这些图像的轮廓 . 但有时这些IC会随机旋转 . 如何将它们拉直到正确的规则矩形?

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

enter image description here

enter image description here

很高兴,如果有人能让我开始如何将这些图像旋转回直角矩形/正方形 . 提前致谢 :)

1 回答

  • 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
    

    这里结果图片:
    chip rectified

相关问题