def thresholding(img_grey):
"""
This functions creates binary images using thresholding
:param img_grey: greyscale image
:return: binary image
"""
# # Adaptive Gaussian
# img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
# Otsu's thresholding after Gaussian filtering
blur = cv.GaussianBlur(img_grey, (5, 5), 0)
ret3, img_binary = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# invert black = 255
ret, thresh1 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV)
return thresh1
python类GaussianBlur()的实例源码
def thresholding(img_grey):
"""
This functions creates binary images using thresholding
:param img_grey: greyscale image
:return: binary image
"""
# # Global
# ret1, thresh1 = cv.threshold(img_grey, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh1)
#
# # Adaptive Mean
# img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
# ret2, thresh2 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh2)
#
# # Adaptive Gaussian
# img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
# ret3, thresh3 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh3)
# Otsu's thresholding after Gaussian filtering
blur = cv.GaussianBlur(img_grey, (5, 5), 0)
ret4, img_otsu = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
ret4, thresh4 = cv.threshold(img_otsu, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh4)
return thresh4
def gaussian_blur(image, sigma=1.0):
"""Applies a gaussian filter to an image, by processing each channel seperately.
Notes: we do not use: scipy.ndimage.filters.gaussian_filter(), because it makes
the image gray-scaled, but with shape [..., 3]
Parameters
----------
image: ndarray
The image to filter. Can have any number of channels, because each is
processed separately.
sigma: float
The sigma level, where a larger number means more blur effect.
Returns
----------
The blurred image.
"""
# apply equal gaussian and use ksize=0 to auto-compute it from sigma
blurred_img = cv2.GaussianBlur(image,(0,0), sigma)
return blurred_img
def calcDirection(img,blockSize):
"""calculate ridge directions in an image, using gradient method
return: ridge directions
"""
sobel_x=np.array([[1, 0, -1],[2, 0, -2],[1, 0, -1]])
sobel_y=np.array([[1, 2, 1],[0, 0, 0],[-1,-2,-1]])
par_x=convolve2d(img,sobel_x,mode='same')
par_y=convolve2d(img,sobel_y,mode='same')
N,M=np.shape(img)
Vx=np.zeros((N/blockSize,M/blockSize))
Vy=np.zeros((N/blockSize,M/blockSize))
for i in xrange(N/blockSize):
for j in xrange(M/blockSize):
a=i*blockSize;b=a+blockSize;c=j*blockSize;d=c+blockSize
Vy[i,j]=2*np.sum(par_x[a:b,c:d]*par_y[a:b,c:d])
Vx[i,j]=np.sum(par_y[a:b,c:d]**2-par_x[a:b,c:d]**2)
gaussianBlurSigma=2; gaussian_block=5
Vy=cv2.GaussianBlur(Vy,(gaussian_block,gaussian_block),gaussianBlurSigma,gaussianBlurSigma)
Vx=cv2.GaussianBlur(Vx,(gaussian_block,gaussian_block),gaussianBlurSigma,gaussianBlurSigma)
theta=0.5*np.arctan2(Vy,Vx)
return theta
def calcWlBox(img, blockSize, boxSize):
resize=5
img=cv2.resize(img,None,fx=resize,fy=resize,interpolation = cv2.INTER_CUBIC)
blockSize=blockSize*resize
boxSize=boxSize*resize
N,M=img.shape
wl=100*np.ones((img.shape[0]/boxSize,img.shape[1]/boxSize))
ii=-1
for i in xrange(blockSize/2,N-blockSize/2,boxSize):
ii += 1
if ii>=N/boxSize:
break
a=i-blockSize/2
b=a+blockSize
jj=-1
for j in xrange(blockSize/2,M-blockSize/2,boxSize):
jj += 1
if jj>=M/boxSize:
break
c=j-blockSize/2
d=c+blockSize
wl[ii,jj]=blkwl(img[a:b,c:d])
gaussianBlurSigma=4; gaussian_block=9
wl=cv2.GaussianBlur(wl,(gaussian_block,gaussian_block),gaussianBlurSigma,gaussianBlurSigma)
return wl/resize
def calcDirection(img,blockSize):
sobel_x=np.array([[1, 0, -1],[2, 0, -2],[1, 0, -1]])
sobel_y=np.array([[1, 2, 1],[0, 0, 0],[-1,-2,-1]])
par_x=convolve2d(img,sobel_x,mode='same')
par_y=convolve2d(img,sobel_y,mode='same')
N,M=np.shape(img)
Vx=np.zeros((N/blockSize,M/blockSize))
Vy=np.zeros((N/blockSize,M/blockSize))
for i in xrange(N/blockSize):
for j in xrange(M/blockSize):
a=i*blockSize;b=a+blockSize;c=j*blockSize;d=c+blockSize
Vy[i,j]=2*np.sum(par_x[a:b,c:d]*par_y[a:b,c:d])
Vx[i,j]=np.sum(par_y[a:b,c:d]**2-par_x[a:b,c:d]**2)
gaussianBlurSigma=2; gaussian_block=5
Vy=cv2.GaussianBlur(Vy,(gaussian_block,gaussian_block),gaussianBlurSigma,gaussianBlurSigma)
Vx=cv2.GaussianBlur(Vx,(gaussian_block,gaussian_block),gaussianBlurSigma,gaussianBlurSigma)
theta=0.5*np.arctan2(Vy,Vx)#+np.pi/2
return theta
def addDirt(img):
rows, cols = img.shape
Dirt = np.ones(img.shape, np.uint8) * 255
change = 0
for i in range(random.randint(0,3)):
change = 1
y = random.randint(0,rows-1)
x = random.randint(0,cols-1)
dy = random.randint(rows//30,rows//5)
dx = random.randint(cols//30,cols//5)
Dirt[y:min(y+dy,rows-1), x:min(x+dx,cols-1)] = random.randint(215,230)
k_size = random.randint(max(rows,cols)//18,max(rows,cols)//14) * 2 + 1
Dirt = cv2.GaussianBlur(Dirt, (k_size, k_size), 0)
if change:
img = np.where(img < 230, img, Dirt)
return img
def get_face_mask(im, landmarks):
im = np.zeros(im.shape[:2], dtype=np.float64)
for landmark in landmarks:
for group in OVERLAY_POINTS:
draw_convex_hull(im,
landmark[group],
color=1)
im = np.array([im, im, im]).transpose((1, 2, 0))
im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0
im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)
return im
# Draw delaunay triangles
def img_sobel_binary(im, blur_sz):
# ??????????????
img_blur = cv2.GaussianBlur(im,blur_sz,0)
if len(img_blur.shape) == 3:
blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)
else:
blur_gray = img_blur
# ??Sobel????
sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3)
abs_sobelx = np.absolute(sobelx)
sobel_8u = np.uint8(abs_sobelx)
img_show_hook("Sobel??", sobel_8u)
# OTSU??????
ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thd_abs = cv2.convertScaleAbs(thd)
bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0)
img_show_hook("OTSU????", bgimg)
return bgimg
def img_sobel_binary(im, blur_sz):
# ??????????????
img_blur = cv2.GaussianBlur(im,blur_sz,0)
if len(img_blur.shape) == 3:
blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)
else:
blur_gray = img_blur
# ??Sobel????
sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3)
abs_sobelx = np.absolute(sobelx)
sobel_8u = np.uint8(abs_sobelx)
img_show_hook("Sobel??", sobel_8u)
# OTSU??????
ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thd_abs = cv2.convertScaleAbs(thd)
bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0)
img_show_hook("OTSU????", bgimg)
return bgimg
def _do_filter(self, frame):
''' Process a single frame. '''
# blur to reduce noise
frame = cv2.GaussianBlur(frame, (5, 5), 0, borderType=cv2.BORDER_CONSTANT)
# threshold to find contiguous regions of "bright" pixels
# ignore all "dark" (<1/8 max) pixels
max = numpy.max(frame)
min = numpy.min(frame)
# if the frame is completely dark, then just return it
if max == min:
return frame
threshold = min + (max - min) / 8
_, frame = cv2.threshold(frame, threshold, 255, cv2.THRESH_BINARY)
# filter out single pixels and other noise
frame = cv2.erode(frame, self._element_shrink)
# restore and join nearby regions (in case one fish has a skinny middle...)
frame = cv2.dilate(frame, self._element_grow)
return frame
def scale_rgb(layers, min_max, lidx):
layers_c = np.empty(layers.shape, dtype='float32')
# Rescale and blur.
for li in range(0, 3):
layer = layers[li]
layer = np.float32(rescale_intensity(layer,
in_range=(min_max[li][0],
min_max[li][1]),
out_range=(0, 1)))
layers_c[lidx[li]] = rescale_intensity(cv2.GaussianBlur(layer,
ksize=(3, 3),
sigmaX=3),
in_range=(0, 1),
out_range=(-1, 1))
return layers_c
def get_contour(self, arg_frame, arg_export_index, arg_export_path, arg_export_filename, arg_binaryMethod):
# Otsu's thresholding after Gaussian filtering
tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(tmp,(5,5),0)
if arg_binaryMethod== 0:
ret, thresholdedImg= cv2.threshold(blur.copy() , self.threshold_graylevel, 255 , 0)
elif arg_binaryMethod == 1:
ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
elif arg_binaryMethod== 2:
thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0)
result = cv2.cvtColor(thresholdedImg, cv2.COLOR_GRAY2RGB)
ctrs, hier = cv2.findContours(thresholdedImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ctrs = filter(lambda x : cv2.contourArea(x) > self.threshold_size , ctrs)
rects = [[cv2.boundingRect(ctr) , ctr] for ctr in ctrs]
for rect , cntr in rects:
cv2.drawContours(result, [cntr], 0, (0, 128, 255), 3)
if arg_export_index:
cv2.imwrite(arg_export_path+ arg_export_filename+'.jpg', result)
print "Get Contour success"
return result
def detect_optic_disk(image_rgb, disk_center, out_name):
scale = 100
w_sum = cv2.addWeighted(image_rgb, 4, cv2.GaussianBlur(image_rgb, (0, 0), scale / 30), -4, 128)# * circular_mask + 128 * (1 - circular_mask)
# Image.fromarray(np.mean(w_sum, axis=2).astype(np.uint8)).save(out_name)
edges = canny(np.mean(w_sum, axis=2).astype(np.uint8), sigma=1.,
low_threshold=50.)#, high_threshold=100.)
result = hough_ellipse(edges, threshold=10, min_size=45, max_size=55)
result.sort(order='accumulator')
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
Image.fromarray(image_rgb).save(out_name)
def kaggle_BG(img, scale):
# Create a mask from which the approximate retinal center can be calculated
guide_mask = create_mask(img)
retina_center = tuple((np.mean(np.argwhere(guide_mask), axis=0)).astype(np.uint8))[::-1]
# Generate a circle of the approximate size, centered based on the guide mask
cf = 1.2
circular_mask = np.zeros(img.shape)
cv2.circle(circular_mask, retina_center, int(scale * cf), (1, 1, 1), -1, 8, 0)
# Compute weight sum of image, blurred image and mask it
w_sum = cv2.addWeighted(img, 4, cv2.GaussianBlur(img, (0, 0), scale / 30), -4, 128) * circular_mask + 128 * (1 - circular_mask)
return w_sum.astype(np.uint8)
# https://github.com/btgraham/SparseConvNet/blob/kaggle_Diabetic_Retinopathy_competition/Data/
# kaggleDiabeticRetinopathy/preprocessImages.py
def analyzeAsymmetric(a,b):
# a = target
# b = current
# if you see a pixel in current that isn't in target, that's really bad
# if you see a pixel and target that isn't an current, that's not so bad
import cv2
kernelSize = blurKernelSize
a = cv2.GaussianBlur(a,(kernelSize,kernelSize),sigmaX = 0)
b = cv2.GaussianBlur(b,(kernelSize,kernelSize),sigmaX = 0)
showImage(a + b)
d = a - b
targetBigger = np.sum(d[d > 0]*d[d > 0])
currentBigger = np.sum(d[d < 0]*d[d < 0])
print "targetBigger = %f"%targetBigger
print "currentBigger = %f"%currentBigger
# showImage(b)
return currentBigger*2 + targetBigger
def find_lines(img, acc_threshold=0.25, should_erode=True):
if len(img.shape) == 3 and img.shape[2] == 3: # if it's color
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img = cv2.GaussianBlur(img, (11, 11), 0)
img = cv2.adaptiveThreshold(
img,
255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
5,
2)
img = cv2.bitwise_not(img)
# thresh = 127
# edges = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)[1]
# edges = cv2.Canny(blur, 500, 500, apertureSize=3)
if should_erode:
element = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
img = cv2.erode(img, element)
theta = np.pi/2000
angle_threshold = 2
horizontal = cv2.HoughLines(
img,
1,
theta,
int(acc_threshold * img.shape[1]),
min_theta=np.radians(90 - angle_threshold),
max_theta=np.radians(90 + angle_threshold))
vertical = cv2.HoughLines(
img,
1,
theta,
int(acc_threshold * img.shape[0]),
min_theta=np.radians(-angle_threshold),
max_theta=np.radians(angle_threshold),
)
horizontal = list(horizontal) if horizontal is not None else []
vertical = list(vertical) if vertical is not None else []
horizontal = [line[0] for line in horizontal]
vertical = [line[0] for line in vertical]
horizontal = np.asarray(horizontal)
vertical = np.asarray(vertical)
return horizontal, vertical
def convert_and_count(target, ext):
for root, dirs, files in os.walktarget):
for f in files:
fname, fext = os.path.splitext(f)
if fext == ext:
img = cv2.imread(os.path.join(root, f), 0)
blur = cv2.GaussianBlur(img, (5, 5), 0)
ret, imgb = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite(os.path.join(root, fname + ".bin.png"), imgb)
cnt = 0
for val in imgb.flat:
if val == 0:
cnt += 1
ratio = cnt / img.size
msg = "%s:\t%.5f" % (f, ratio)
print(msg)
def threshold_img(img):
"""
Simple wrap-up function for cv2.threshold()
"""
is_color = len(img.shape) == 3
is_grey = len(img.shape) == 2
t = threshold_value(img)
if is_color:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
elif is_grey:
gray = img.copy()
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
(_, thresh) = cv2.threshold(blurred, t*255, 1, cv2.THRESH_BINARY_INV)
return thresh
def threshold_img(img):
"""
Simple wrap-up function for cv2.threshold()
"""
is_color = len(img.shape) == 3
is_grey = len(img.shape) == 2
t = threshold_value(img)
if is_color:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
elif is_grey:
gray = img.copy()
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
(_, thresh) = cv2.threshold(blurred, t*255, 1, cv2.THRESH_BINARY_INV)
return thresh