'''
针对于paper.jpg中的图像,将纸的目标物体(轮廓)变成白色,背景变为黑色
'''
import cv2
import numpy as np
img = cv2.imread('../data/paper.jpg')
cv2.imshow('img', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
cv2.imshow('thresh', thresh)
sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 1, ksize=3)
cv2.imshow('sobel', sobel)
lap = cv2.Laplacian(gray, cv2.CV_8U, ksize=3)
cv2.imshow('lap', lap)
# 高斯模糊
blur = cv2.GaussianBlur(gray, (7, 7), 0)
canny = cv2.Canny(blur, 30, 120)
cv2.imshow('canny', canny)
contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# print(len(contours))
# print(cv2.contourArea(contours[0]))
# print(cv2.contourArea(contours[1]))
cnts = sorted(contours, key=cv2.contourArea, reverse=True)
docCnt = cnts[0] # 目标轮阔
cv2.drawContours(img, [docCnt], -1, (0, 255, 0), 2)
cv2.imshow('res', img)
#拟合多边形,找到目标轮廓的四个角的顶点
eps = 0.02 * cv2.arcLength(docCnt, True)
approx = cv2.approxPolyDP(docCnt, eps, True)
# print(approx)
for peak in approx:
center = tuple(peak[0])
cv2.circle(img, center, 8, (0, 0, 255), 2)
cv2.imshow('res_point', img)
#构建变换之前的顶点坐标:左上角,左下角,右下角,右上角
approx = approx.reshape(4, 2).astype(np.float32)
print(approx)
#求出纸的高度和宽度
h = np.sqrt((approx[0][0] - approx[1][0]) ** 2 + (approx[0][1] - approx[1][1]) ** 2)
w = np.sqrt((approx[0][0] - approx[3][0]) ** 2 + (approx[0][1] - approx[3][1]) ** 2)
#构建变换之后的顶点坐标:左上角,左下角,右下角,右上角
dst = np.array([[0, 0], [0, h], [w, h], [w, 0]], dtype=np.float32)
M = cv2.getPerspectiveTransform(approx, dst)
res = cv2.warpPerspective(img, M, (int(w), int(h)))
cv2.imshow('res_warp', res)
cv2.waitKey()
cv2.destroyAllWindows()
效果如下:
最后矫正效果如下: