import numpy as np
import cv2
import matplotlib.pyplot as plt
def CrossPoint(line1, line2):
x0, y0, x1, y1 = line1
x2, y2, x3, y3 = line2
dx1 = x1 - x0
dy1 = y1 - y0
dx2 = x3 - x2
dy2 = y3 - y2
D1 = x1 * y0 - x0 * y1
D2 = x3 * y2 - x2 * y3
y = float(dy1 * D2 - D1 * dy2) / (dy1 * dx2 - dx1 * dy2)
x = float(y * dx1 - D1) / dy1
return (int(x), int(y))
#四个点换顺序
def SortPoint(points):
sp = sorted(points, key=lambda x: (int(x[1]), int(x[0])))
if sp[0][0] > sp[1][0]:
sp[0], sp[1] = sp[1], sp[0]
if sp[2][0] > sp[3][0]:
sp[2], sp[3] = sp[3], sp[2]
return sp
def imgcorr(src):
rgbsrc = src.copy()
graysrc = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
blurimg = cv2.GaussianBlur(graysrc, (3, 3), 0)
Cannyimg = cv2.Canny(blurimg, 35, 189)
#显示边沿
cv2.namedWindow("Cannyimg", 0)
cv2.resizeWindow("Cannyimg", 500, 480)
cv2.imshow("Cannyimg", Cannyimg)
#显示边沿线条的位置
lines = cv2.HoughLinesP(Cannyimg, 1, np.pi / 180, threshold=30, minLineLength=320, maxLineGap=40)
print(len(lines))
lines=np.squeeze(lines)
cv2.line(rgbsrc, (lines[0][0], lines[0][1]), (lines[0][2], lines[0][3]), (255, 0, 0), 6)#红//0
cv2.line(rgbsrc, (lines[1][0], lines[1][1]), (lines[1][2], lines[1][3]), (255, 255, 0), 6)#///1
cv2.line(rgbsrc, (lines[2][0], lines[2][1]), (lines[2][2], lines[2][3]), (255, 255,255), 6)#白///2
cv2.line(rgbsrc, (lines[3][0], lines[3][1]), (lines[3][2], lines[3][3]), (0, 0, 255), 6)#蓝3
cv2.line(rgbsrc, (lines[4][0], lines[4][1]), (lines[4][2], lines[4][3]), (0, 255, 0), 6)#绿///4
lineimage = cv2.cvtColor(rgbsrc, cv2.COLOR_BGR2RGB)
plt.imshow(lineimage)
plt.show()
#计算角点
points = np.zeros((4, 2), dtype="float32")
points[0] = CrossPoint(lines[0], lines[2])
points[1] = CrossPoint(lines[0], lines[4])
points[2] = CrossPoint(lines[1], lines[2])
points[3] = CrossPoint(lines[1], lines[4])
print(points)
#排序角点
sp = SortPoint(points)
width = int(np.sqrt(((sp[0][0] - sp[1][0]) ** 2) + (sp[0][1] - sp[1][1]) ** 2))
height = int(np.sqrt(((sp[0][0] - sp[2][0]) ** 2) + (sp[0][1] - sp[2][1]) ** 2))
dstrect = np.array([
[0, 0],
[width - 1, 0],
[0, height - 1],
[width - 1, height - 1]], dtype="float32")#目标矩阵
transform = cv2.getPerspectiveTransform(np.array(sp), dstrect)#利用原图角点和目标角点计算透视变换矩阵
warpedimg = cv2.warpPerspective(src, transform, (width, height))
return warpedimg
if __name__ == '__main__':
# src = cv2.imread("C:/Users/ubuntu/Desktop/input.jpg")
src = cv2.imread("../data/02.jpg")
dst = imgcorr(src)
cv2.namedWindow("Image", 0)
cv2.resizeWindow("Image", 600, 600)
cv2.imshow("Image", dst)
cv2.waitKey(0)
# cv2.imwrite("output.jpg", dst)
python+cv2图片矫正
最新推荐文章于 2024-06-11 10:03:52 发布