我有这样的输入图像
裁剪红点很容易,因为它是一个矩形。如果 2、3、6 和 7 上的红点动态移动到绿点,我该如何裁剪。这些要点可能会改变我如何在程序中动态裁剪。
结果可能是这样的
我尝试了 Warppperspective,但无法获得预期的结果。 程序是这样的
import matplotlib.pyplot as plt
import numpy as np
import cv2
img = cv2.imread('sudoku_result.png')
pts1 = np.float32([[100,60],[260,60],[100,180],[260,180],[100,300],[260,300]])
pts2 = np.float32([[20,60],[340,60],[60,180],[300,180][100,300],[260,300]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(360,360))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
我是图像处理的新手,想知道哪种方法最好。
最佳答案
裁剪由 (minX,minY,maxX,maxY) 创建的封闭矩形,然后对于裁剪图像中的每个像素,您可以检查原始点创建的多边形内部的点是否以及外部的点您置零的原始形状。
代码:
import cv2
import numpy as np
# Read a image
I = cv2.imread('i.png')
# Define the polygon coordinates to use or the crop
polygon = [[[20,110],[450,108],[340,420],[125,420]]]
# First find the minX minY maxX and maxY of the polygon
minX = I.shape[1]
maxX = -1
minY = I.shape[0]
maxY = -1
for point in polygon[0]:
x = point[0]
y = point[1]
if x < minX:
minX = x
if x > maxX:
maxX = x
if y < minY:
minY = y
if y > maxY:
maxY = y
# Go over the points in the image if thay are out side of the emclosing rectangle put zero
# if not check if thay are inside the polygon or not
cropedImage = np.zeros_like(I)
for y in range(0,I.shape[0]):
for x in range(0, I.shape[1]):
if x < minX or x > maxX or y < minY or y > maxY:
continue
if cv2.pointPolygonTest(np.asarray(polygon),(x,y),False) >= 0:
cropedImage[y, x, 0] = I[y, x, 0]
cropedImage[y, x, 1] = I[y, x, 1]
cropedImage[y, x, 2] = I[y, x, 2]
# Now we can crop again just the envloping rectangle
finalImage = cropedImage[minY:maxY,minX:maxX]
cv2.imwrite('finalImage.png',finalImage)
最终图片:
如果要拉伸(stretch)裁剪后的图片
# Now strectch the polygon to a rectangle. We take the points that
polygonStrecth = np.float32([[0,0],[finalImage.shape[1],0],[finalImage.shape[1],finalImage.shape[0]],[0,finalImage.shape[0]]])
# Convert the polygon corrdanite to the new rectnagle
polygonForTransform = np.zeros_like(polygonStrecth)
i = 0
for point in polygon[0]:
x = point[0]
y = point[1]
newX = x - minX
newY = y - minY
polygonForTransform[i] = [newX,newY]
i += 1
# Find affine transform
M = cv2.getPerspectiveTransform(np.asarray(polygonForTransform).astype(np.float32), np.asarray(polygonStrecth).astype(np.float32))
# Warp one image to the other
warpedImage = cv2.warpPerspective(finalImage, M, (finalImage.shape[1], finalImage.shape[0]))
cv2.imshow('a',warpedImage)
关于opencv - 根据所选坐标裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493195/