<jupyter_start><jupyter_text>Normalized CutThis example constructs a Region Adjacency Graph (RAG) and recursively performsa Normalized Cut on it [1]_.References----------.. [1] <NAME>.; <NAME>., "Normalized cuts and image segmentation",       Pattern Analysis and Machine Intelligence,       IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.<jupyter_code>from skimage import data, segmentation, color, io
from skimage.future import graph
from matplotlib import pyplot as plt
from skimage.measure import regionprops
from skimage import draw
import cv2

img = cv2.imread("E:/MTECH-IIITB/2018Aug-Dec/DIP-II/MalikSeg_paper/code/BSR/BSDS500/data/images/train/198004.jpg", cv2.IMREAD_GRAYSCALE)
#img = cv2.resize(img, dsize=(128, 192), interpolation=cv2.INTER_CUBIC)
#img = data.coffee()

labels1 = segmentation.slic(img, compactness=30, n_segments=400)
out1 = color.label2rgb(labels1, img, kind='avg')

g = graph.rag_mean_color(img, labels1, mode='similarity')

#for n,d in g.nodes_iter(data=True):
 #   print(d)

%matplotlib inline
def display_edges(image, g):
    """Draw edges of a RAG on its image
 
    Returns a modified image with the edges drawn. Edges with high weight are
    drawn in red and edges with a low weight are drawn in green. Nodes are drawn
    in yellow.
 
    Parameters
    ----------
    image : ndarray
        The image to be drawn on.
    g : RAG
        The Region Adjacency Graph.
    threshold : float
        Only edges in `g` below `threshold` are drawn.
 
    Returns:
    out: ndarray
        Image with the edges drawn.
    """
 
    image = image.copy()
    max_weight = max([d['weight'] for x, y, d in g.edges_iter(data=True)])
    min_weight = min([d['weight'] for x, y, d in g.edges_iter(data=True)])
 
    for edge in g.edges_iter():
        n1, n2 = edge
 
        r1, c1 = map(int, g.node[n1]['centroid'])
        r2, c2 = map(int, g.node[n2]['centroid'])
 
        green = 0,1,0
        red = 1,0,0
 
        line  = draw.line(r1, c1, r2, c2)
        circle = draw.circle(r1,c1,2)
        norm_weight = ( g[n1][n2]['weight'] - min_weight ) / ( max_weight - min_weight )
 
        image[line] = 0,0,1
        image[circle] = 1,1,0
 
    return image
labels1 = labels1+1
regions = regionprops(labels1)
g = graph.rag_mean_color(img, labels1, mode='similarity')
for region in regions:
    g.node[region['label']]['centroid'] = region['centroid']
def show_img(img):
 
    width = img.shape[1]/75.0
    height = img.shape[0]*width/img.shape[1]
    f = plt.figure(figsize=(width, height))
    plt.imshow(img)
label_rgb = color.label2rgb(labels1, img, kind='avg')
show_img(label_rgb)
label_rgb = display_edges(label_rgb, g)
show_img(label_rgb)
print(g[383][382]['weight'])
print(g[382][383]['weight'])
d = list(g.nodes_iter(data=True))
g.add_node(1,mylabel=1)
g.node[1]['labels'][0]
print(g.node[1]['labels'][0])
print(g.node[100]['labels'][0])
print(g.node[300]['labels'][0])

labels2 = graph.cut_normalized(labels1, g)
out2 = color.label2rgb(labels2, img, kind='avg')

fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(6, 8))

ax[0].imshow(out1)
ax[1].imshow(out2)

for a in ax:
    a.axis('off')

plt.tight_layout()
plt.show()
ncut_img = labels2
plt.axis('off')
plt.imshow(ncut_img)
plt.show()
from skimage.future.graph import rag
import networkx as nx
from matplotlib import pyplot as plt
import numpy as np
def display(g, title):
    """Displays a graph with the given title."""
    pos = nx.circular_layout(g)
    plt.figure()
    plt.title(title)
    nx.draw(g, pos)
    nx.draw_networkx_edge_labels(g, pos, font_size=20)
display(g, "Original Graph")
plt.show()
print(labels2[100:102,:])
print(g[200])
for i in range(3,-3,-1):
    print(i)<jupyter_output>3
2
1
0
-1
-2
{'fraction_non_alphanumeric': 0.14820759764579988, 'fraction_numerical': 0.04039593365436062, 'mean_word_length': 3.72692793931732, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '594833', 'license': 'MIT', 'n_tokens_mistral': 1461, 'n_tokens_neox': 1368, 'n_words': 349, 'path': 'code_sources/plot_ncut.ipynb', 'repo_name': 'saikat-d/LeungMalikSegmentation', 'size': '3740'}