将转换矩阵应用于opencv中的点列表(Python)

Hay*_*row 3 python opencv

我无法理解cv2.transform的文档。有人会怜悯并解释一下吗(在Python中)?

我有绘制多边形,将其填充并旋转图像的代码

import numpy as np  
import cv2

dx,dy = 400,400
centre = dx//2,dy//2
img = np.zeros((dy,dx),np.uint8)

# construct a long thin triangle with the apex at the centre of the image
polygon = np.array([(0,0),(100,10),(100,-10)],np.int32)
polygon += np.int32(centre)

# draw the filled-in polygon and then rotate the image
cv2.fillConvexPoly(img,polygon,(255))
M = cv2.getRotationMatrix2D(centre,20,1) # M.shape =  (2, 3)
rotatedimage = cv2.warpAffine(img,M,img.shape)
Run Code Online (Sandbox Code Playgroud)

我想先旋转多边形然后再绘制

# this is clumsy, I have to extend each vector,
# apply the matrix to each extended vector,
# and turn the list of transformed vectors into an numpy array
extendedpolygon = np.hstack([polygon,np.ones((3,1))])
rotatedpolygon = np.int32([M.dot(x) for x in extendedpolygon])
cv2.fillConvexPoly(img,rotatedpolygon,(127))
Run Code Online (Sandbox Code Playgroud)

我想在一个函数调用中做到这一点,但我做对了

# both of these calls produce the same error
cv2.transform(polygon,M)
cv2.transform(polygon.T,M)
# OpenCV Error: Assertion failed (scn == m.cols || scn + 1 == m.cols) in transform, file /home/david/opencv/modules/core/src/matmul.cpp, line 1947
Run Code Online (Sandbox Code Playgroud)

我怀疑这是短语“ src –输入数组必须具有与m.cols或m.cols-1一样多的通道(1至4)”的意思。我以为polygon.T作为三个坐标,而x和y部分作为单独的通道是合格的,但遗憾的是没有。

我知道对C ++也提出了同样的问题,我想用Python给出答案。

Hay*_*row 5

感谢Micka,他为我指出了一个可行的例子。这是为我的问题提供答案的代码。

import numpy as np  
import cv2

dx,dy = 400,400
centre = dx//2,dy//2
img = np.zeros((dy,dx),np.uint8)

# construct a long thin triangle with the apex at the centre of the image
polygon = np.array([(0,0),(100,10),(100,-10)],np.int32)
polygon += np.int32(centre)

# draw the filled-in polygon and then rotate the image
cv2.fillConvexPoly(img,polygon,(255))
M = cv2.getRotationMatrix2D(centre,20,1) # M.shape =  (2, 3)
rotatedimage = cv2.warpAffine(img,M,img.shape)

# as an alternative, rotate the polygon first and then draw it

# these are alternative ways of coding the working example
# polygon.shape is 3,2

# magic that makes sense if one understands numpy arrays
poly1 = np.reshape(polygon,(3,1,2))
# slightly more accurate code that doesn't assumy the polygon is a triangle
poly2 = np.reshape(polygon,(polygon.shape[0],1,2))
# turn each point into an array of points
poly3 = np.array([[p] for p in polygon])
# use an array of array of points 
poly4 = np.array([polygon])
# more magic 
poly5 = np.reshape(polygon,(1,3,2))

for poly in (poly1,poly2,poly3,poly4,poly5):
    newimg = np.zeros((dy,dx),np.uint8)
    rotatedpolygon = cv2.transform(poly,M)
    cv2.fillConvexPoly(newimg,rotatedpolygon,(127))
Run Code Online (Sandbox Code Playgroud)

老实说,我不明白为什么cv2.fillConvexPoly()接受前三个答案,但这似乎是非常宽容的,而且我仍然不明白这些答案如何映射到文档。