Skip to content

Instantly share code, notes, and snippets.

@joaopedro-fg
Created December 18, 2019 14:26
Show Gist options
  • Select an option

  • Save joaopedro-fg/cc5a0ca43f3e9a605ed4314af97e6b73 to your computer and use it in GitHub Desktop.

Select an option

Save joaopedro-fg/cc5a0ca43f3e9a605ed4314af97e6b73 to your computer and use it in GitHub Desktop.
#Imports
import os
from argparse import ArgumentParser
from skimage.segmentation import slic
from skimage import data, io, segmentation, color
from skimage.future import graph
import numpy as np
#Arguments
parser = ArgumentParser()
parser.add_argument("--region", dest="region")
args = parser.parse_args()
#SLIC
def slicfy(img):
compactness = 20
n_segments = 10000
segments = slic(img, compactness=compactness, n_segments=n_segments)
final = color.label2rgb(segments, img, kind='avg')
return [final, segments]
#RAG Merging
def _weight_mean_color(graph, src, dst, n):
diff = graph.node[dst]['mean color'] - graph.node[n]['mean color']
diff = np.linalg.norm(diff)
return {'weight': diff}
def merge_mean_color(graph, src, dst):
graph.node[dst]['total color'] += graph.node[src]['total color']
graph.node[dst]['pixel count'] += graph.node[src]['pixel count']
graph.node[dst]['mean color'] = (graph.node[dst]['total color'] / graph.node[dst]['pixel count'])
def ragfy(img, segments):
g = graph.rag_mean_color(img, segments)
labels2 = graph.merge_hierarchical(segments, g, thresh=35, rag_copy=False,
in_place_merge=True,
merge_func=merge_mean_color,
weight_func=_weight_mean_color)
out = color.label2rgb(labels2, img, kind='avg')
out = segmentation.mark_boundaries(out, labels2, (0, 0, 0))
return out
#MAIN
def main():
#Create 'SLIC' dir
for y in range(1, 7):
pathS = f"../REGIONS/Region {y}/SLIC"
if not os.path.isdir(pathS):
os.mkdir(pathS)
# pathR = f"../Region {y}/SLIC+RAG"
# if not os.path.isdir(pathR):
# os.mkdir(pathR)
#Iterate over Zooms High
path = f"../REGIONS/Region {y}/eye alt 330/HD/Zooms High"
directory = os.fsencode(path)
for file in os.listdir(directory):
filename = os.fsdecode(file)
original = io.imread(path + "/" + filename)
slic = slicfy(original)
# rag = ragfy(original, slic[1])
# io.imsave(pathS + "/" + filename.split('.')[0] + ".png", slic[0])
# io.imsave(pathR + "/" + filename.split('.')[0] + ".png", rag)
# Save segments
name = filename.split('.')[0]
file1 = open(f"..REGIONS/Region {y}/SLIC/{name}.txt", "w")
for x in slic[1]:
for z in x:
file1.write(str(z) + " ")
file1.write("\n")
file1.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment