def get_init_process_img(roi_img):
"""
?????????????????????????????????????
:param roi_img: ndarray
:return: ndarray
"""
h = cv2.Sobel(roi_img, cv2.CV_32F, 0, 1, -1)
v = cv2.Sobel(roi_img, cv2.CV_32F, 1, 0, -1)
img = cv2.add(h, v)
img = cv2.convertScaleAbs(img)
img = cv2.GaussianBlur(img, (3, 3), 0)
ret, img = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)
kernel = np.ones((1, 1), np.uint8)
img = cv2.erode(img, kernel, iterations=1)
img = cv2.dilate(img, kernel, iterations=2)
img = cv2.erode(img, kernel, iterations=1)
img = cv2.dilate(img, kernel, iterations=2)
img = auto_canny(img)
return img
python类erode()的实例源码
def erode(im, iterations=1):
return cv2.erode(im, None, iterations=iterations)
def erode_dilate(im, iterations=1):
return dilate(erode(im, iterations=iterations), iterations)
def dilate_erode(im, iterations=1):
return erode(dilate(im, iterations=iterations), iterations)
def execute_Morphing(proxy,obj):
try: img=obj.sourceObject.Proxy.img.copy()
except: img=cv2.imread(__dir__+'/icons/freek.png')
ks=obj.kernel
kernel = np.ones((ks,ks),np.uint8)
if obj.filter == 'dilation':
dilation = cv2.dilate(img,kernel,iterations = 1)
img=dilation
if obj.filter == 'erosion':
dilation = cv2.erode(img,kernel,iterations = 1)
img=dilation
if obj.filter == 'opening':
dilation = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
img=dilation
if obj.filter == 'closing':
dilation = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
img=dilation
obj.Proxy.img = img
#
# property functions for HoughLines
#
def checkForSkin(IMG10):
high,widt=IMG10.shape[:2]
B1=np.reshape(np.float32(IMG10[:,:,0]),high*widt)#B
G1=np.reshape(np.float32(IMG10[:,:,1]),high*widt)#G
R1=np.reshape(np.float32(IMG10[:,:,2]),high*widt)#Rs
#print high,widt
h3=np.zeros((high,widt,3),np.uint8)
#cv2.imshow("onetime",h)
tem=np.logical_and(np.logical_and(np.logical_and(np.logical_and(R1 > 95, G1 > 40),np.logical_and(B1 > 20, (np.maximum(np.maximum(R1,G1),B1) - np.minimum(np.minimum(R1,G1),B1)) > 15)),R1>B1),np.logical_and(np.absolute(R1-G1) > 15,R1>G1))
h5=np.array(tem).astype(np.uint8,order='C',casting='unsafe')
h5=np.reshape(h5,(high,widt))
h3[:,:,0]=h5
h3[:,:,1]=h5
h3[:,:,2]=h5
#cv2.imshow("thirdtime",h3)
kernel1 = np.ones((3,3),np.uint8)
closedH3=np.copy(h3)
for i in range(5):
closedH3 = cv2.erode(closedH3,kernel1)
for i in range(5):
closedH3 = cv2.dilate(closedH3,kernel1)
#cv2.imshow("closedH3",closedH3)
# closedH3 = cv2.cvtColor(closedH3, cv2.COLOR_BGR2RGB)
return closedH3
ColoredObjectDetector.py 文件源码
项目:robot-camera-platform
作者: danionescu0
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def find(self, image):
hsv_frame = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_frame, self.__hsv_bounds[0], self.__hsv_bounds[1])
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
contours = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
if len(contours) == 0:
return (False, False)
largest_contour = max(contours, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(largest_contour)
M = cv2.moments(largest_contour)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
return (center, radius)
def convert_to_linedrawing(self, luminous_image_data):
kernel = numpy.ones((3, 3), numpy.uint8)
linedrawing = cv2.Canny(luminous_image_data, 5, 125)
linedrawing = cv2.bitwise_not(linedrawing)
linedrawing = cv2.erode(linedrawing, kernel, iterations=1)
linedrawing = cv2.dilate(linedrawing, kernel, iterations=1)
return linedrawing
def morphology(msk):
assert isinstance(msk, numpy.ndarray), 'msk must be a numpy array'
assert msk.ndim == 2, 'msk must be a greyscale image'
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
msk = cv2.erode(msk, kernel, iterations=1)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
msk = cv2.morphologyEx(msk, cv2.MORPH_CLOSE, kernel)
msk[msk < 128] = 0
msk[msk > 127] = 255
return msk
def build_mask(self, image):
""" Build the mask to find the path edges """
kernel = np.ones((3, 3), np.uint8)
img = cv2.bilateralFilter(image, 9, 75, 75)
img = cv2.erode(img, kernel, iterations=1)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, self.lower_gray, self.upper_gray)
mask2 = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
mask2 = cv2.erode(mask2, kernel)
mask2 = cv2.dilate(mask2, kernel, iterations=1)
return mask2
def __cv_erode(src, kernel, anchor, iterations, border_type, border_value):
"""Expands area of lower value in an image.
Args:
src: A numpy.ndarray.
kernel: The kernel for erosion. A numpy.ndarray.
iterations: the number of times to erode.
border_type: Opencv enum that represents a border type.
border_value: value to be used for a constant border.
Returns:
A numpy.ndarray after erosion.
"""
return cv2.erode(src, kernel, anchor, iterations = (int) (iterations +0.5),
borderType = border_type, borderValue = border_value)
def __cv_erode(src, kernel, anchor, iterations, border_type, border_value):
"""Expands area of lower value in an image.
Args:
src: A numpy.ndarray.
kernel: The kernel for erosion. A numpy.ndarray.
iterations: the number of times to erode.
border_type: Opencv enum that represents a border type.
border_value: value to be used for a constant border.
Returns:
A numpy.ndarray after erosion.
"""
return cv2.erode(src, kernel, anchor, iterations = (int) (iterations +0.5),
borderType = border_type, borderValue = border_value)
def extract_bv(image):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast_enhanced_green_fundus = clahe.apply(image)
# applying alternate sequential filtering (3 times closing opening)
r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
f5 = clahe.apply(f4)
# removing very small contours through area parameter noise removal
ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
mask = np.ones(f5.shape[:2], dtype="uint8") * 255
im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) <= 200:
cv2.drawContours(mask, [cnt], -1, 0, -1)
im = cv2.bitwise_and(f5, f5, mask=mask)
ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)
newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
# removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
# vessels and also in an interval of area
fundus_eroded = cv2.bitwise_not(newfin)
xmask = np.ones(image.shape[:2], dtype="uint8") * 255
x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in xcontours:
shape = "unidentified"
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
shape = "circle"
else:
shape = "veins"
if(shape=="circle"):
cv2.drawContours(xmask, [cnt], -1, 0, -1)
finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)
blood_vessels = cv2.bitwise_not(finimage)
dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
#dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
blood_vessels_1 = cv2.bitwise_not(dilated)
return blood_vessels_1
def extract_bv(image):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast_enhanced_green_fundus = clahe.apply(image)
# applying alternate sequential filtering (3 times closing opening)
r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
f5 = clahe.apply(f4)
# removing very small contours through area parameter noise removal
ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
mask = np.ones(f5.shape[:2], dtype="uint8") * 255
im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) <= 200:
cv2.drawContours(mask, [cnt], -1, 0, -1)
im = cv2.bitwise_and(f5, f5, mask=mask)
ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)
newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
# removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
# vessels and also in an interval of area
fundus_eroded = cv2.bitwise_not(newfin)
xmask = np.ones(image.shape[:2], dtype="uint8") * 255
x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in xcontours:
shape = "unidentified"
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
shape = "circle"
else:
shape = "veins"
if(shape=="circle"):
cv2.drawContours(xmask, [cnt], -1, 0, -1)
finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)
blood_vessels = cv2.bitwise_not(finimage)
dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
#dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
blood_vessels_1 = cv2.bitwise_not(dilated)
return blood_vessels_1
def skin_filter(cfg, vd):
df = pd.read_csv(vd.photo_csv, index_col=0)
numbers = df.number.tolist()
notface = []
for number in numbers:
lower = np.array([0, 48, 80], dtype = "uint8")
upper = np.array([13, 255, 255], dtype = "uint8")
image = cv2.imread('%s/%d.png' % (vd.photo_dir, number), cv2.IMREAD_COLOR)
converted = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
skinMask = cv2.inRange(converted, lower, upper)
# apply a series of erosions and dilations to the mask
# using an elliptical kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
skinMask = cv2.erode(skinMask, kernel, iterations = 2)
skinMask = cv2.dilate(skinMask, kernel, iterations = 2)
# blur the mask to help remove noise, then apply the
# mask to the frame
skinMask = cv2.GaussianBlur(skinMask, (3, 3), 0)
skin = cv2.bitwise_and(image, image, mask = skinMask)
if len(skin.nonzero()[0]) < cfg.min_skin_pixels:
notface.append(number)
print '%d/%d are faces' % ( len(df) - len(notface), len(df) )
df['face']= 1
df.loc[df.number.isin(notface),'face'] = -99
df.to_csv(vd.photo_csv)
def makeMask(hsv_frame, color_Range):
mask = cv2.inRange( hsv_frame, color_Range[0], color_Range[1])
# Morphosis next ...
eroded = cv2.erode( mask, kernel, iterations=1)
dilated = cv2.dilate( eroded, kernel, iterations=1)
return dilated
# Contours on the mask are detected.. Only those lying in the previously set area
# range are filtered out and the centroid of the largest of these is drawn and returned
def calibrateColor(color, def_range):
global kernel
name = 'Calibrate '+ color
cv2.namedWindow(name)
cv2.createTrackbar('Hue', name, 0, 180, nothing)
cv2.createTrackbar('Sat', name, 0, 255, nothing)
cv2.createTrackbar('Val', name, 0, 255, nothing)
while(1):
ret , frameinv = cap.read()
frame=cv2.flip(frameinv ,1)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hue = cv2.getTrackbarPos('Hue', name)
sat = cv2.getTrackbarPos('Sat', name)
val = cv2.getTrackbarPos('Val', name)
lower = np.array([hue-20,sat,val])
upper = np.array([hue+20,255,255])
mask = cv2.inRange(hsv, lower, upper)
eroded = cv2.erode( mask, kernel, iterations=1)
dilated = cv2.dilate( eroded, kernel, iterations=1)
cv2.imshow(name, dilated)
k = cv2.waitKey(5) & 0xFF
if k == ord(' '):
cv2.destroyWindow(name)
return np.array([[hue-20,sat,val],[hue+20,255,255]])
elif k == ord('d'):
cv2.destroyWindow(name)
return def_range
def makeMask(hsv_frame, color_Range):
mask = cv2.inRange( hsv_frame, color_Range[0], color_Range[1])
# Morphosis next ...
eroded = cv2.erode( mask, kernel, iterations=1)
dilated = cv2.dilate( eroded, kernel, iterations=1)
return dilated
# Contours on the mask are detected.. Only those lying in the previously set area
# range are filtered out and the centroid of the largest of these is drawn and returned
def calibrateColor(color, def_range):
global kernel
name = 'Calibrate '+ color
cv2.namedWindow(name)
cv2.createTrackbar('Hue', name, 0, 180, nothing)
cv2.createTrackbar('Sat', name, 0, 255, nothing)
cv2.createTrackbar('Val', name, 0, 255, nothing)
while(1):
ret , frameinv = cap.read()
frame=cv2.flip(frameinv ,1)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hue = cv2.getTrackbarPos('Hue', name)
sat = cv2.getTrackbarPos('Sat', name)
val = cv2.getTrackbarPos('Val', name)
lower = np.array([hue-20,sat,val])
upper = np.array([hue+20,255,255])
mask = cv2.inRange(hsv, lower, upper)
eroded = cv2.erode( mask, kernel, iterations=1)
dilated = cv2.dilate( eroded, kernel, iterations=1)
cv2.imshow(name, dilated)
k = cv2.waitKey(5) & 0xFF
if k == ord(' '):
cv2.destroyWindow(name)
return np.array([[hue-20,sat,val],[hue+20,255,255]])
elif k == ord('d'):
cv2.destroyWindow(name)
return def_range
def makeMask(hsv_frame, color_Range):
mask = cv2.inRange( hsv_frame, color_Range[0], color_Range[1])
# Morphosis next ...
eroded = cv2.erode( mask, kernel, iterations=1)
dilated = cv2.dilate( eroded, kernel, iterations=1)
return dilated
# Contours on the mask are detected.. Only those lying in the previously set area
# range are filtered out and the centroid of the largest of these is drawn and returned