本文整理汇总了Python中cv2.MORPH_OPEN属性的典型用法代码示例。如果您正苦于以下问题:Python cv2.MORPH_OPEN属性的具体用法?Python cv2.MORPH_OPEN怎么用?Python cv2.MORPH_OPEN使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类cv2
的用法示例。
在下文中一共展示了cv2.MORPH_OPEN属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: colorTarget
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def colorTarget(color_range=((0, 0, 0), (255, 255, 255))):
image = cam.newImage()
if filter == 'RGB':
frame_to_thresh = image.copy()
else:
frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # convert image to hsv colorspace RENAME THIS TO IMAGE_HSV
thresh = cv2.inRange(frame_to_thresh, color_range[0], color_range[1])
# apply a blur function
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) # Apply blur
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # Apply blur 2nd iteration
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] # generates number of contiguous "1" pixels
if len(cnts) > 0: # begin processing if there are "1" pixels discovered
c = max(cnts, key=cv2.contourArea) # return the largest target area
((x, y), radius) = cv2.minEnclosingCircle(c)
return np.array([round(x, 1), round(y, 1), round(radius, 1)])
else:
return np.array([None, None, 0])
示例2: returnMask
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def returnMask(self, frame, morph_opening=True, blur=True, kernel_size=5, iterations=1):
"""Given an input frame return the black/white mask.
This version of the function does not use the blur and bitwise
operations, then the resulting frame contains white pixels
in correspondance of the skin found during the searching process.
@param frame the original frame (color)
"""
#Convert to HSV and eliminate pixels outside the range
frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
frame_filtered = cv2.inRange(frame_hsv, self.min_range, self.max_range)
if(morph_opening==True):
kernel = np.ones((kernel_size,kernel_size), np.uint8)
frame_filtered = cv2.morphologyEx(frame_filtered, cv2.MORPH_OPEN, kernel, iterations=iterations)
#Applying Gaussian Blur
if(blur==True):
frame_filtered = cv2.GaussianBlur(frame_filtered, (kernel_size,kernel_size), 0)
return frame_filtered
示例3: motionDetected
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def motionDetected(self, new_frame):
frame = self.preprocessInputFrame(new_frame)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
gray = cv.GaussianBlur(gray, (21, 21), 0)
if self.prevFrame is None:
self.prevFrame = gray
return False
frameDiff = cv.absdiff(gray, self.prevFrame)
# kernel = np.ones((5, 5), np.uint8)
opening = cv.morphologyEx(frameDiff, cv.MORPH_OPEN, None) # noqa
closing = cv.morphologyEx(frameDiff, cv.MORPH_CLOSE, None) # noqa
ret1, th1 = cv.threshold(frameDiff, 10, 255, cv.THRESH_BINARY)
height = np.size(th1, 0)
width = np.size(th1, 1)
nb = cv.countNonZero(th1)
avg = (nb * 100) / (height * width) # Calculate the average of black pixel in the image
self.prevFrame = gray
# cv.DrawContours(currentframe, self.currentcontours, (0, 0, 255), (0, 255, 0), 1, 2, cv.CV_FILLED)
# cv.imshow("frame", current_frame)
ret = avg > self.threshold # If over the ceiling trigger the alarm
if ret:
self.updateMotionDetectionDts()
return ret
示例4: denoise
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def denoise(mask, eps):
"""Removes noise from a mask.
Args:
mask: the mask to remove noise from.
eps: the morphological operation's kernel size for noise removal, in pixel.
Returns:
The mask after applying denoising.
"""
struct = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (eps, eps))
return cv2.morphologyEx(mask, cv2.MORPH_OPEN, struct)
示例5: gradient_and_binary
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def gradient_and_binary(img_blurred, image_name='1.jpg', save_path='./'): # 将灰度图二值化,后面两个参数调试用
"""
求取梯度,二值化
:param img_blurred: 滤波后的图片
:param image_name: 图片名,测试用
:param save_path: 保存路径,测试用
:return: 二值化后的图片
"""
gradX = cv2.Sobel(img_blurred, ddepth=cv2.CV_32F, dx=1, dy=0)
gradY = cv2.Sobel(img_blurred, ddepth=cv2.CV_32F, dx=0, dy=1)
img_gradient = cv2.subtract(gradX, gradY)
img_gradient = cv2.convertScaleAbs(img_gradient) # sobel算子,计算梯度, 也可以用canny算子替代
# 这里改进成自适应阈值,貌似没用
img_thresh = cv2.adaptiveThreshold(img_gradient, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, -3)
# cv2.imwrite(os.path.join(save_path, img_name + '_binary.jpg'), img_thresh) # 二值化 阈值未调整好
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
img_closed = cv2.morphologyEx(img_thresh, cv2.MORPH_CLOSE, kernel)
img_closed = cv2.morphologyEx(img_closed, cv2.MORPH_OPEN, kernel)
img_closed = cv2.erode(img_closed, None, iterations=9)
img_closed = cv2.dilate(img_closed, None, iterations=9) # 腐蚀膨胀
# 这里调整了kernel大小(减小),腐蚀膨胀次数后(增大),出错的概率大幅减小
return img_closed
示例6: _filter_image
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def _filter_image(self, image):
_, thresh = cv2.threshold(image, 200, 255, cv2.THRESH_BINARY)
opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, (5, 5), iterations=3)
return cv2.bitwise_not(opened)
示例7: roiMask
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def roiMask(image, boundaries):
scale = max([1.0, np.average(np.array(image.shape)[0:2] / 400.0)])
shape = (int(round(image.shape[1] / scale)), int(round(image.shape[0] / scale)))
small_color = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)
# reduce details and remove noise for better edge detection
small_color = cv2.bilateralFilter(small_color, 8, 64, 64)
small_color = cv2.pyrMeanShiftFiltering(small_color, 8, 64, maxLevel=1)
small = cv2.cvtColor(small_color, cv2.COLOR_BGR2HSV)
hue = small[::, ::, 0]
intensity = cv2.cvtColor(small_color, cv2.COLOR_BGR2GRAY)
edges = extractEdges(hue, intensity)
roi = roiFromEdges(edges)
weight_map = weightMap(hue, intensity, edges, roi)
_, final_mask = cv2.threshold(roi, 5, 255, cv2.THRESH_BINARY)
small = cv2.bitwise_and(small, small, mask=final_mask)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))
for (lower, upper) in boundaries:
lower = np.array([lower, 80, 50], dtype="uint8")
upper = np.array([upper, 255, 255], dtype="uint8")
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(small, lower, upper)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
final_mask = cv2.bitwise_and(final_mask, mask)
# blur the mask for better contour extraction
final_mask = cv2.GaussianBlur(final_mask, (5, 5), 0)
return (final_mask, weight_map, scale)
示例8: morph_postprocess
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def morph_postprocess(img):
kernel = np.ones((5,5),np.uint8)
# --- opening ---
img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
# --- closing ---
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
return img
示例9: morph_process
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def morph_process(image):
"""
图像形态学变化
:param image:
:return:
"""
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
close_image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
open_image = cv2.morphologyEx(close_image, cv2.MORPH_OPEN, kernel)
return open_image
示例10: segment
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def segment(self, image):
mask = np.array(image[:, :, 1] < self._threshold).astype(np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
return mask * 255
示例11: morphological_transformations
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def morphological_transformations(im_thresh, morpho_type="CLOSE", kernel_shape=(5, 5), kernel_type="ELLIPSE"):
"""
Take black & white image and apply morphological transformation
:param im_thresh: Black & White Image
:param morpho_type: CLOSE/OPEN/ERODE/DILATE => See on OpenCV/Google if you do not know these words
:param kernel_shape: tuple corresponding to the size of the kernel
:param kernel_type: RECT/ELLIPSE/CROSS => see on OpenCV
:return: image after processing
"""
if kernel_type == "CROSS":
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, kernel_shape)
elif kernel_type == "RECT":
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, kernel_shape)
else:
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernel_shape)
if morpho_type == "OPEN":
morph_type = cv2.MORPH_OPEN
elif morpho_type == "DILATE":
morph_type = cv2.MORPH_DILATE
elif morpho_type == "ERODE":
morph_type = cv2.MORPH_ERODE
else:
morph_type = cv2.MORPH_CLOSE
return cv2.morphologyEx(im_thresh, morph_type, kernel)
# Contours
示例12: removeBG
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def removeBG(frame):
fgmask = bgModel.apply(frame,learningRate=learningRate)
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
# res = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
kernel = np.ones((3, 3), np.uint8)
fgmask = cv2.erode(fgmask, kernel, iterations=1)
res = cv2.bitwise_and(frame, frame, mask=fgmask)
return res
示例13: reduce_noise_edges
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def reduce_noise_edges(im):
structuring_element = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
opening = cv2.morphologyEx(im, cv2.MORPH_OPEN, structuring_element)
maxed_rows = rank_filter(opening, -4, size=(1, 20))
maxed_cols = rank_filter(opening, -4, size=(20, 1))
debordered = np.minimum(np.minimum(opening, maxed_rows), maxed_cols)
return debordered
示例14: __call__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def __call__(self, img_dict):
data_get_func = img_dict['meta']['get_item_func']
curr_idx = img_dict['meta']['idx']
max_idx = img_dict['meta']['max_idx']
other_idx = np.random.randint(0, max_idx)
data4augm = data_get_func(other_idx)
while (curr_idx == other_idx) or (self.same_label and data4augm['label'] != img_dict['label']):
other_idx = np.random.randint(0, max_idx)
data4augm = data_get_func(other_idx)
depth4augm = data4augm['depth'].resize(img_dict['depth'].size)
mask4augm = np.array(depth4augm.convert('L')) > 0
mask4augm = cv2.morphologyEx(mask4augm.astype(np.uint8),
cv2.MORPH_OPEN,
self.kernel_orgl)
mask = np.array(img_dict['depth'].convert('L')) > 0
mask = cv2.morphologyEx(mask.astype(np.uint8),
cv2.MORPH_OPEN,
self.kernel_augm)
mask = (mask == mask4augm) & (mask)
mask = np.repeat(np.expand_dims(mask, 2), 3, axis=2)
keys = ['depth', 'ir']
for key in keys:
np_img = np.array(img_dict[key]) * mask
img_dict[key] = Image.fromarray(np_img)
return img_dict
示例15: colorSegmentation
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import MORPH_OPEN [as 别名]
def colorSegmentation(img, blur_radius, radius, open_radius, color):
#Get color of point in image
#print self.point
#Grab the R, G, B channels as separate matrices
#use cv2.threshold on each of them
#AND the three images together
bw = numpy.ones(img.shape[0:2], numpy.uint8)
maxvals = [179, 255, 255]
for i in range(3):
minval = color[i] - radius
maxval = color[i] + radius
if radius > color[i]:
minval = 0
elif radius + color[i] > maxvals[i]:
minval = color[i] - radius
channel = img[:, :, i]
retval, minthresh = cv2.threshold(channel, minval, 255, cv2.THRESH_BINARY)
retval, maxthresh = cv2.threshold(channel, maxval, 255, cv2.THRESH_BINARY_INV)
bw = cv2.bitwise_and(bw, minthresh)
bw = cv2.bitwise_and(bw, maxthresh)
bw *= 255
if open_radius != 0:
open_kernel = numpy.array([open_radius, open_radius])
bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, open_kernel, iterations = 4)
return bw