Pythonでの実装
出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2022/05/13 17:53 UTC 版)
「大津の二値化法」の記事における「Pythonでの実装」の解説
この実装にはNumPyライブラリが必要である def compute_otsu_criteria(im, th): # create the thresholded image thresholded_im = np.zeros(im.shape) thresholded_im[im >= th] = 1 # compute weights nb_pixels = im.size nb_pixels1 = np.count_nonzero(th) weight1 = nb_pixels1 / nb_pixels weight0 = 1 - weight1 # if one the classes is empty, eg all pixels are below or above the threshold, that threshold will not be considered # in the search for the best threshold if weight1 == 0 or weight0 == 0: return np.nan # find all pixels belonging to each class val_pixels1 = im[thresholded_im == 1] val_pixels0 = im[thresholded_im == 0] # compute variance of these classes var0 = np.var(val_pixels0) if len(val_pixels0) > 0 else 0 var1 = np.var(val_pixels1) if len(val_pixels1) > 0 else 0 return weight0 * var0 + weight1 * var1im = # load your image as a numpy array.# For testing purposes, one can use for example im = np.random.randint(0,255, size = (50,50))# testing all thresholds from 0 to the maximum of the imagethreshold_range = range(np.max(im)+1)criterias = [compute_otsu_criteria(im, th) for th in threshold_range]# best threshold is the one minimizing the Otsu criteriabest_threshold = threshold_range[np.argmin(criterias)] OpenCVやScikit-imageなどの画像処理専用のPythonライブラリは、アルゴリズムの組み込み実装を提案する。
※この「Pythonでの実装」の解説は、「大津の二値化法」の解説の一部です。
「Pythonでの実装」を含む「大津の二値化法」の記事については、「大津の二値化法」の概要を参照ください。
Pythonでの実装(再帰なし)
出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2018/02/13 08:17 UTC 版)
「深さ優先探索」の記事における「Pythonでの実装(再帰なし)」の解説
以下は、2頂点間の経路を探す例。なお、これを幅優先探索でやると、辺の重みなしの最短経路問題になる。 def depthFirstSearch( start, goal ): stack = Stack() start.setVisited() stack.push( start ) while not stack.empty(): node = stack.top() if node == goal: return stack # stack には2頂点間の経路が入っている else: child = node.findUnvisitedChild() if child == none: stack.pop() else: child.setVisited() stack.push( child )
※この「Pythonでの実装(再帰なし)」の解説は、「深さ優先探索」の解説の一部です。
「Pythonでの実装(再帰なし)」を含む「深さ優先探索」の記事については、「深さ優先探索」の概要を参照ください。
- Pythonでの実装のページへのリンク