尝试连接图片中的各个点时遇到麻烦(见下文)。
现在,我的代码如下:
first_time = resulting_coords[0:40]
for i in range(len(first_time)):
if(i < (len(first_time))-1):
cv2.line(copy_test_image[0], (resulting_coords[i,0],resulting_coords[i,1]),
(resulting_coords[i+1,0],resulting_coords[i+1,1]), (0,0,225), 2)
elif(i>=(len(first_time))-1):
# print(i)
cv2.line(copy_test_image[0], (resulting_coords[i,0],resulting_coords[i,1]),
(resulting_coords[0,0],resulting_coords[0,1]), (0,0,225), 2)
实际上给出了我想要的结果:
但是我无法提取这些线的像素坐标。
我尝试使用一个相当复杂的函数,该函数使用P1(x1,y1)和P2(x2,y2)点,并将它们与具有像素坐标的线相连:
def pixels_in_shape(x1, y1, x2, y2, img):
P1=[x1,y1]
P2=[x2,y2]
#define local variables for readability
imageH = img.shape[0]
imageW = img.shape[1]
P1X = int(P1[0])
P1Y = int(P1[1])
P2X = int(P2[0])
P2Y = int(P2[1])
#difference and absolute difference between points
#used to calculate slope and relative location between points
dX = P2X - P1X
dY = P2Y - P1Y
dXa = np.abs(dX)
dYa = np.abs(dY)
#predefine numpy array for output based on distance between points
itbuffer = np.zeros(shape=(int(np.maximum(dYa,dXa)),3),dtype=np.float32)
itbuffer.fill(np.nan)
#Obtain coordinates along the line using a form of Bresenham's algorithm
negY = P1Y > P2Y
negX = P1X > P2X
if P1X == P2X: #vertical line segment
itbuffer[:,0] = P1X
if negY:
itbuffer[:,1] = np.arange(P1Y,P1Y - dYa,-1)
else:
itbuffer[:,1] = np.arange(P1Y,P1Y + dYa)
elif P1Y == P2Y: #horizontal line segment
itbuffer[:,1] = P1Y
if negX:
itbuffer[:,0] = np.arange(P1X,P1X-dXa,-1)
else:
itbuffer[:,0] = np.arange(P1X,P1X+dXa)
else: #diagonal line segment
steepSlope = dYa > dXa
if steepSlope:
slope=dX/dY
if negY:
itbuffer[:,1] = np.arange(P1Y,P1Y-dYa,-1)
else:
itbuffer[:,1] = np.arange(P1Y,P1Y+dYa)
itbuffer[:,0] = (slope*(itbuffer[:,1]-P1Y)).astype(np.int) + P1X
else:
slope=dY/dX
if negX:
itbuffer[:,0] = np.arange(P1X,P1X-dXa,-1)
else:
itbuffer[:,0] = np.arange(P1X,P1X+dXa)
itbuffer[:,1] = (slope*(itbuffer[:,0]-P1X)).astype(np.int) + P1Y
#Remove points outside of image
colX = itbuffer[:,0]
colY = itbuffer[:,1]
itbuffer = itbuffer[(colX >= 0) & (colY >=0) & (colX<imageW) & (colY<imageH)]
#Get intensities from img ndarray
itbuffer[:,2] = img[itbuffer[:,1].astype(np.uint),itbuffer[:,0].astype(np.uint)]
return itbuffer
但是,这将导致以下输出(显然是错误的):
请问您如何解决这个问题? 我需要连接这些点,因为我试图提取点所指示的边界内的区域。
**
编辑:已解决。使用的功能
**(Modifying Bresenham's line algorithm)
def bresenham_line(x0, y0, x1, y1):
steep = abs(y1 - y0) > abs(x1 - x0)
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
switched = False
if x0 > x1:
switched = True
x0, x1 = x1, x0
y0, y1 = y1, y0
if y0 < y1:
ystep = 1
else:
ystep = -1
deltax = x1 - x0
deltay = abs(y1 - y0)
error = -deltax / 2
y = y0
line = []
for x in range(x0, x1 + 1):
if steep:
line.append((y,x))
else:
line.append((x,y))
error = error + deltay
if error > 0:
y = y + ystep
error = error - deltax
if switched:
line.reverse()
return line