资源简介
基于Opencv,使用python语言,以图割算法实现的图像分割。
代码片段和文件信息
# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use(‘TkAgg‘)
from numpy import *
import numpy
import maxflow
from PIL import Image
from matplotlib import pyplot as plt
from pylab import *
import cv2
#The function implements graph cut by partitioning a directed graph into two disjoint sets foreground and background...
def graph(file # input image
k # kappa value --> similar pixels have weight close to kappa
s # Sigma value --> determines how fast the values decay towards zero with increasing dissimilarity.
fore # foreground area ---> should be input by the user manually.
back): # background area ---> should be input by the user manually.
I = (Image.open(file).convert(‘L‘)) # read image L = R * 299/1000 + G * 587/1000 + B * 114/1000
If = I.crop(fore) # take a part of the foreground
Ib = I.crop(back) # take a part of the background
IIfIb = array(I)array(If)array(Ib) # convert all the images to arrays to calculation
IfmeanIbmean = mean(cv2.calcHist([If][0]None[256][0256]))mean(cv2.calcHist([Ib][0]None[256][0256])) #Taking the mean of the histogram
FB = ones(shape = I.shape)ones(shape = I.shape) #initalizing the foreground/background probability vector
Im = I.reshape(-11) #Coverting the image array to a vector for ease.
mn = I.shape[0]I.shape[1]# copy the size
gpic = maxflow.Graph[int](mn)maxflow.Graph[int]() # define the graph
structure = np.array([[inf 0 0]
[inf 0 0]
[inf 0 0]
]) # initializing the structure....
sourcesinkJ = m*nm*n+1I # Defining the Source and Sink (terminal)nodes.
nodesnodeids = g.add_nodes(m*n)pic.add_grid_nodes(J.shape) # Adding non-nodes
pic.add_grid_edges(nodeids0)pic.add_grid_tedges(nodeids J 255-J)
gr = pic.maxflow()
IOut = pic.get_grid_segments(nodeids)
for i in range(I.shape[0]): # Defining the Probability function....
for j in range(I.shape[1]):
F[ij] = -log(abs(I[ij] - Ifmean)/(abs(I[ij] - Ifmean)+abs(I[ij] - Ibmean))) # Probability of a pixel being foreground
B[ij] = -log(abs(I[ij] - Ibmean)/(abs(I[ij] - Ibmean)+abs(I[ij] - Ifmean))) # Probability of a pixel being background
FB = F.reshape(-11)B.reshape(-11) # convertingb to column vector for ease
for i in range(Im.shape[0]):
Im[i] = Im[i] / linalg.norm(Im[i]) # normalizing the input image vector
w = structure # defining the weight
for i in range(m*n):#checking the 4-neighborhood pixels
ws=(F[i]/(F[i]+B[i])) # source weight
wt=(B[i]/(F[i]+B[i])) # sink weight
g.add_tedge(iws[0]wt) # edges between pixels and terminal
if i%n != 0: # for left pixels
w = k*exp(-(abs(Im[i]-Im[i-1])**2)/s) # the cost function for two p
评论
共有 条评论