[英]How to find a shape inside a Numpy 2D array having an contour?
我有一個形狀輪廓cnt
,我需要在二維數組中找到它,我有一個 target_index 變量,它用於查找所需的區域,但我需要在其中查找cnt
輪廓。
import numpy as np
x = np.linspace(0,1000, int(1000/50))
y = np.linspace(0,1000, int(1000/50))
X,Y = np.meshgrid(x,y)
source = np.column_stack([X.ravel(), Y.ravel()]).astype(int)
destination = source.copy()
cnt = [[550, 42],
[600, 42],
[690, 273],
[640, 273]]
# Need to use cnt here
target_index = np.where(np.logical_and(destination[:,1]==789,destination[:,0]>=421))
destination[target_index]
scope = destination[target_index]
scope[:,0] = scope[:,0] + 10
destination[target_index] = scope
destination[target_index]
# Remap
grid_x, grid_y = np.mgrid[0:800, 0:800]
grid_z = griddata(source, destination, (grid_x, grid_y), method='cubic')
map_x = np.append([], [ar[:,1] for ar in grid_z]).reshape(800,800).astype('float32')
map_y = np.append([], [ar[:,0] for ar in grid_z]).reshape(800,800).astype('float32')
warped_image = cv2.remap(img, map_x, map_y, cv2.INTER_CUBIC)
cv2.drawContours(warped_image,[cnt],0,(0,0,0),2)
可以使用其他方法,但首選np.where
。
除非您將自己限制在某些多邊形上,否則我認為使用np.where
來執行此操作將非常困難。
以下是如何使用matplotlib
的Path
object 來解決問題(改編此解決方案):
import numpy as np
from matplotlib.path import Path
x = np.linspace(0,1000, int(1000/50))
y = np.linspace(0,1000, int(1000/50))
X,Y = np.meshgrid(x,y)
source = np.column_stack([X.ravel(), Y.ravel()]).astype(int)
cnt = [[550, 42],
[600, 42],
[690, 273],
[640, 273]]
p = Path(cnt)
grid = p.contains_points(source)
mask = grid.reshape(20, 20)
然后看看結果:
import matplotlib.pyplot as plt
plt.imshow(mask)
這使:
在linspace
中使用更多點以獲得更高分辨率的結果。
從你的問題來看,你正在申請身體變形,對我來說這個選項是最方便的,因為你可以為你創建任何輪廓。
# Left hand contour
pt1 = (int_12, int_13)
pt2 = (int_17, int_16)
pt3 = (int_18, int_19)
pt4 = (int_14, int_15)
lh_cnt = np.array([pt1, pt2, pt3, pt4])
offset = int(hand_lenght / 28)
for x in destination:
inside_lh = cv2.pointPolygonTest(lh_cnt, (x[0], x[1]), False)
elif inside_lh > 0:
x[0] = x[0] - offset
# Warping
grid_x, grid_y = np.mgrid[0:self.width, 0:self.height]
grid_z = griddata(source, destination, (grid_x, grid_y), method='cubic')
map_x = np.append([], [ar[:,0] for ar in grid_z]).reshape(self.width, self.height).astype('float32')
map_y = np.append([], [ar[:,1] for ar in grid_z]).reshape(self.width, self.height).astype('float32')
warped_image = cv2.transpose(cv2.remap(img, map_x, map_y, cv2.INTER_LANCZOS4))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.