# 波峰波谷的判断

import numpy as np

def get_peaks_troughs(h,rangesize):
peaks = list()
troughs = list()
S = 0
for x in range(1,len(h)-1):
if S == 0:
if h[x] > h[x+1]:
S = 1 ## down
else:
S = 2 ## up
elif S == 1:
if h[x] < h[x+1]:
S = 2
## from down to up
if len(troughs):
## check if need merge
(prev_x,prev_trough) =  troughs[-1]
if x - prev_x < rangesize:
if prev_trough > h[x]:
troughs[-1] = (x,h[x])
else:
troughs.append((x,h[x]))
else:
troughs.append((x,h[x]))

elif S == 2:
if h[x] > h[x+1]:
S = 1
## from up to down
if len(peaks):
prev_x,prev_peak =  peaks[-1]
if x - prev_x < rangesize:
if prev_peak < h[x]:
peaks[-1] = (x,h[x])
else:
peaks.append((x,h[x]))
else:
peaks.append((x,h[x]))

return peaks,troughs

if __name__ == "__main__":
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img =  255 - img

Y,X = img.shape
print Y,X

h = np.zeros((X,1))
for i in range(X):
for j in range(Y):
if img[j,i] > 0:
h[i] = Y - j

peaks,troughs = get_peaks_troughs(h,10)

plt.subplot(1,2,1)
plt.imshow(img)
plt.subplot(1,2,2)
plt.plot(np.arange(len(h)),h)
for x,y in peaks:
plt.text(x,y,y,fontsize=10,verticalalignment="bottom",horizontalalignment="center")
for x,y in troughs:
plt.text(x,y,y,fontsize=10,verticalalignment="top",horizontalalignment="center")

plt.show()

peaks,troughs = get_peaks_troughs(h,50)  ##  跨度修改成５０后

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120