我现在有一张图片图片上有一个围棋棋盘围棋棋盘边上有一块黑色区域其中围棋棋盘有四个红色的点用于定位黑色区域中有一些白色棋子。现在我已知四个红色的点的坐标位置经过透视变换之后棋盘变正了但是不包含黑色区域。我要怎么做才能在已知四个红色点的坐标位置的条件下经过透视变换使得棋盘变正并且变正图片中包含经过相同透视变换之后的黑色区域?先分析后用python代码供我参考一下
分析:
-
通过四个红色点的坐标位置确定透视变换矩阵。
-
将原始图片进行透视变换,得到变换后的棋盘图片。
-
对于黑色区域,需要先确定其在原始图片中的位置,然后通过透视变换矩阵将其转换到变换后的棋盘图片中。
-
将变换后的棋盘图片和黑色区域图片进行叠加,得到最终的图片。
Python代码:
- 导入必要的库
import cv2 import numpy as np
- 读取原始图片并显示
img = cv2.imread('input.jpg') cv2.imshow('input', img) cv2.waitKey(0)
- 确定四个红色点的坐标位置
红色点的坐标位置
points = [(100, 100), (500, 100), (100, 500), (500, 500)]
- 通过四个红色点的坐标位置确定透视变换矩阵
变换前的四个点
pts1 = np.float32(points)
变换后的四个点
pts2 = np.float32([[0, 0], [500, 0], [0, 500], [500, 500]])
透视变换矩阵
M = cv2.getPerspectiveTransform(pts1, pts2)
- 将原始图片进行透视变换,得到变换后的棋盘图片
变换后的图片大小
rows, cols = (500, 500)
变换后的图片
dst = cv2.warpPerspective(img, M, (cols, rows))
显示变换后的图片
cv2.imshow('output', dst) cv2.waitKey(0)
- 对于黑色区域,需要先确定其在原始图片中的位置,然后通过透视变换矩阵将其转换到变换后的棋盘图片中
黑色区域在原始图片中的位置
x, y, w, h = (50, 50, 400, 400)
黑色区域在变换后的图片中的位置
dst_x, dst_y, dst_w, dst_h = cv2.perspectiveTransform(np.array([[[x, y]], [[x+w, y]], [[x, y+h]], [[x+w, y+h]]]), M) dst_x, dst_y = np.int32(dst_x), np.int32(dst_y) dst_w, dst_h = np.int32(dst_w), np.int32(dst_h)
从原始图片中截取黑色区域
roi = img[y:y+h, x:x+w]
将黑色区域转换到变换后的图片中
dst_roi = cv2.warpPerspective(roi, M, (dst_w-dst_x, dst_h-dst_y))
- 将变换后的棋盘图片和黑色区域图片进行叠加,得到最终的图片
将黑色区域图片叠加到变换后的棋盘图片中
dst[dst_y:dst_h, dst_x:dst_w] = dst_roi
显示最终的图片
cv2.imshow('final', dst) cv2.waitKey(0)
完整代码如下:
import cv2 import numpy as np
读取原始图片并显示
img = cv2.imread('input.jpg') cv2.imshow('input', img) cv2.waitKey(0)
红色点的坐标位置
points = [(100, 100), (500, 100), (100, 500), (500, 500)]
变换前的四个点
pts1 = np.float32(points)
变换后的四个点
pts2 = np.float32([[0, 0], [500, 0], [0, 500], [500, 500]])
透视变换矩阵
M = cv2.getPerspectiveTransform(pts1, pts2)
变换后的图片大小
rows, cols = (500, 500)
变换后的图片
dst = cv2.warpPerspective(img, M, (cols, rows))
显示变换后的图片
cv2.imshow('output', dst) cv2.waitKey(0)
黑色区域在原始图片中的位置
x, y, w, h = (50, 50, 400, 400)
黑色区域在变换后的图片中的位置
dst_x, dst_y, dst_w, dst_h = cv2.perspectiveTransform(np.array([[[x, y]], [[x+w, y]], [[x, y+h]], [[x+w, y+h]]]), M) dst_x, dst_y = np.int32(dst_x), np.int32(dst_y) dst_w, dst_h = np.int32(dst_w), np.int32(dst_h)
从原始图片中截取黑色区域
roi = img[y:y+h, x:x+w]
将黑色区域转换到变换后的图片中
dst_roi = cv2.warpPerspective(roi, M, (dst_w-dst_x, dst_h-dst_y))
将黑色区域图片叠加到变换后的棋盘图片中
dst[dst_y:dst_h, dst_x:dst_w] = dst_roi
显示最终的图片
cv2.imshow('final', dst) cv2.waitKey(0
原文地址: https://www.cveoy.top/t/topic/c3tK 著作权归作者所有。请勿转载和采集!