這是一個有趣的有向圖問題。在每個切片中,最後一列與第一列的距離誤差。構建圖形後,您只需要找到頭部,然後沿著最小成本路徑走即可。我已經勾畫了一個你可以從頭開始的腳本:
import cv2
import numpy as np
import matplotlib.pyplot as plt
cut_thr = 0.19 # magic number , but kind of arbitrary as if you add a cut, you just make your graph bigger
im = cv2.imread(r'example.png').astype(np.float32)/255 #read image
im = cv2.cvtColor(im,cv2.COLOR_BGR2RGB)
dx=np.abs(np.diff(im,axis=1)) #x difference
dx = np.max(dx,axis=2) #max on all color channels
dx=np.median(dx,axis=0) #max on y axis
plt.plot(dx)
cuts = np.r_[0,np.where(dx>cut_thr)[0]+1,im.shape[1]] #inclusive borders
cuts = [im[:,cuts[i]:cuts[i+1]] for i in range(len(cuts)-1)]
n = len(cuts)
fig,ax = plt.subplots(1,n)
for a,c in zip(ax,cuts):
a.imshow(c, aspect='auto')
a.axis('off')
d = np.ones((n,n))*np.nan # directed connectivity
for y in range(n):
for x in range(y+1,n):
d[y][x]=np.median(np.abs(cuts[y][:,-1]-cuts[x][:,0]))
d[x][y]=np.median(np.abs(cuts[x][:,-1]-cuts[y][:,0]))
src = np.arange(n)
dst=np.nanargmin(d,axis=1) # the dest of source is the one with the lowest error
indx=np.where(d==np.nanmin(d))[0][-1] #head, where to begin
im = cuts[indx]
for i in range(n-1):
indx=dst[src[indx]]
im = np.concatenate([im,cuts[indx]],axis=1)
plt.figure()
plt.imshow(im, aspect='equal')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句