本文整理汇总了Python中cv2.subtract方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.subtract方法的具体用法?Python cv2.subtract怎么用?Python cv2.subtract使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.subtract方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _pre_process_input_minimal
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def _pre_process_input_minimal(self, img, mask, t, darker_fg=True):
if self._buff_grey is None:
self._buff_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
if mask is None:
mask = np.ones_like(self._buff_grey) * 255
cv2.cvtColor(img,cv2.COLOR_BGR2GRAY, self._buff_grey)
cv2.erode(self._buff_grey, self._erode_kern, dst=self._buff_grey)
if darker_fg:
cv2.subtract(255, self._buff_grey, self._buff_grey)
if mask is not None:
cv2.bitwise_and(self._buff_grey, mask, self._buff_grey)
return self._buff_grey
示例2: skeletonize
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def skeletonize(image_in):
'''Inputs and grayscale image and outputs a binary skeleton image'''
size = np.size(image_in)
skel = np.zeros(image_in.shape, np.uint8)
ret, image_edit = cv2.threshold(image_in, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
done = False
while not done:
eroded = cv2.erode(image_edit, element)
temp = cv2.dilate(eroded, element)
temp = cv2.subtract(image_edit, temp)
skel = cv2.bitwise_or(skel, temp)
image_edit = eroded.copy()
zeros = size - cv2.countNonZero(image_edit)
if zeros == size:
done = True
return skel
示例3: maximizeContrast
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def maximizeContrast(imgGrayscale):
height, width = imgGrayscale.shape
imgTopHat = np.zeros((height, width, 1), np.uint8)
imgBlackHat = np.zeros((height, width, 1), np.uint8)
structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement)
imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement)
imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat)
imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat)
return imgGrayscalePlusTopHatMinusBlackHat
# end function
示例4: imnormalize_
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def imnormalize_(img, mean, std, to_rgb=True):
"""Inplace normalize an image with mean and std.
Args:
img (ndarray): Image to be normalized.
mean (ndarray): The mean to be used for normalize.
std (ndarray): The std to be used for normalize.
to_rgb (bool): Whether to convert to rgb.
Returns:
ndarray: The normalized image.
"""
# cv2 inplace normalization does not accept uint8
assert img.dtype != np.uint8
mean = np.float64(mean.reshape(1, -1))
stdinv = 1 / np.float64(std.reshape(1, -1))
if to_rgb:
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) # inplace
cv2.subtract(img, mean, img) # inplace
cv2.multiply(img, stdinv, img) # inplace
return img
示例5: preprocess
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def preprocess(image):
# load the image
image = cv2.imread(args["image"])
#resize image
image = cv2.resize(image,None,fx=0.7, fy=0.7, interpolation = cv2.INTER_CUBIC)
#convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#calculate x & y gradient
gradX = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)
# subtract the y-gradient from the x-gradient
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
# blur the image
blurred = cv2.blur(gradient, (3, 3))
# threshold the image
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
thresh = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
return thresh
示例6: generateDoGImages
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def generateDoGImages(gaussian_images):
"""Generate Difference-of-Gaussians image pyramid
"""
logger.debug('Generating Difference-of-Gaussian images...')
dog_images = []
for gaussian_images_in_octave in gaussian_images:
dog_images_in_octave = []
for first_image, second_image in zip(gaussian_images_in_octave, gaussian_images_in_octave[1:]):
dog_images_in_octave.append(subtract(second_image, first_image)) # ordinary subtraction will not work because the images are unsigned integers
dog_images.append(dog_images_in_octave)
return array(dog_images)
###############################
# Scale-space extrema related #
###############################
示例7: skeletize
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def skeletize(img):
size = np.size(img)
skel = np.zeros(img.shape, np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
done = False
while not done:
eroded = cv2.erode(img, element)
temp = cv2.dilate(eroded, element)
temp = cv2.subtract(img, temp)
skel = cv2.bitwise_or(skel, temp)
img = eroded.copy()
zeroes = size - cv2.countNonZero(img)
if zeroes == size:
done = True
return skel
示例8: getAllSquareRecord
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def getAllSquareRecord(all_square_list,types):
print("将所有的方块与类型进行比较,转置成数字矩阵...")
record = [] # 整个记录的二维数组
line = [] # 记录一行
for square in all_square_list: # 把所有的方块和保存起来的所有类型做对比
num = 0
for type in types: # 所有类型
res = cv2.subtract(square,type) # 作比较
if not np.any(res): # 如果两个图片一样
line.append(num) # 将类型的数字记录进这一行
break # 并且跳出循环
num += 1 # 如果没有匹配上,则类型数加1
if len(line) == V_NUM: # 如果校验完这一行已经有了11个数据,则另起一行
record.append(line)
line = []
print(record)
return record
# 自动消除
示例9: subtract_bgnd
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def subtract_bgnd(self, image):
# new method using bitwise not
def _remove_func(_img, _func, _bg):
#the reason to use opencv2 instead of numpy is to avoid buffer overflow
#https://stackoverflow.com/questions/45817037/opencv-image-subtraction-vs-numpy-subtraction/45817868
new_img = np.zeros_like(_img); #maybe can do this in place
if image.ndim == 2:
_func(_img, _bg, new_img)
else:
for ii, this_frame in enumerate(_img):
_func(this_frame, _bg, new_img[ii])
return new_img
bg = self.bgnd.astype(np.uint8)
if self.is_light_background:
notbg = ~bg
ss = _remove_func(image, cv2.add, notbg)
else: # fluorescence
ss = _remove_func(image, cv2.subtract, bg)
ss = np.clip( ss ,1,255);
return ss
示例10: skeletonize
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def skeletonize(img):
""" OpenCV function to return a skeletonized version of img, a Mat object"""
# hat tip to http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/
img = img.copy() # don't clobber original
skel = img.copy()
skel[:,:] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
while True:
eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)
temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)
temp = cv2.subtract(img, temp)
skel = cv2.bitwise_or(skel, temp)
img[:,:] = eroded[:,:]
if cv2.countNonZero(img) == 0:
break
return skel
示例11: test_write_image_to_disk
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def test_write_image_to_disk():
"""Test for write_image_to_disk
"""
print("testing write_image_to_disk")
# load the image from disk
bgr_image = load_image("images/logo.png")
# write image to disk
write_image_to_disk("images/temp.png", bgr_image)
# load the image temp from disk
temp = load_image("images/temp.png")
# now we check that the two images are equal
assert bgr_image.shape == temp.shape
difference = cv2.subtract(bgr_image, temp)
b, g, r = cv2.split(difference)
assert cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0
示例12: calculate_diff
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def calculate_diff(self, frame):
if self.avgframe is not None:
subframe = cv2.subtract(frame, self.avgframe)
grayscaled = cv2.cvtColor(subframe, cv2.COLOR_BGR2GRAY)
retval2,th1 = cv2.threshold(grayscaled,35,255,cv2.THRESH_BINARY)
self.avgframe = cv2.addWeighted(frame, 0.1, self.avgframe, 0.9, 0.0)
th1 = th1 / 255
w, h = th1.shape
sum = cv2.sumElems(th1)[0]/(w*h)
return sum
else:
self.avgframe = frame
return 0.0
# Test the code.
示例13: gradient_and_binary
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [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
示例14: describe
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def describe(self, image):
# convert the image to the HSV color space and initialize
# the features used to quantify the image
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
features = []
# grab the dimensions and compute the center of the image
(h, w) = image.shape[:2]
(cX, cY) = (int(w * 0.5), int(h * 0.5))
# divide the image into four rectangles/segments (top-left,
# top-right, bottom-right, bottom-left)
segments = [(0, cX, 0, cY), (cX, w, 0, cY),
(cX, w, cY, h), (0, cX, cY, h)]
# construct an elliptical mask representing the center of the
# image
(axesX, axesY) = (int(w * 0.75) / 2, int(h * 0.75) / 2)
ellipMask = np.zeros(image.shape[:2], dtype="uint8")
cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)
# loop over the segments
for (startX, endX, startY, endY) in segments:
# construct a mask for each corner of the image, subtracting
# the elliptical center from it
cornerMask = np.zeros(image.shape[:2], dtype="uint8")
cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
cornerMask = cv2.subtract(cornerMask, ellipMask)
# extract a color histogram from the image, then update the
# feature vector
hist = self.histogram(image, cornerMask)
features.extend(hist)
# extract a color histogram from the elliptical region and
# update the feature vector
hist = self.histogram(image, ellipMask)
features.extend(hist)
# return the feature vector
return features
示例15: describe
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import subtract [as 别名]
def describe(self, image):
# convert the image to the HSV color space and initialize
# the features used to quantify the image
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
features = []
# grab the dimensions and compute the center of the image
(h, w) = image.shape[:2]
(cX, cY) = (int(w * 0.5), int(h * 0.5))
# divide the image into four rectangles/segments (top-left,
# top-right, bottom-right, bottom-left)
segments = [(0, cX, 0, cY), (cX, w, 0, cY), (cX, w, cY, h),
(0, cX, cY, h)]
# construct an elliptical mask representing the center of the
# image
(axesX, axesY) = (int(w * 0.75) // 2, int(h * 0.75) // 2)
ellipMask = np.zeros(image.shape[:2], dtype = "uint8")
cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)
# loop over the segments
for (startX, endX, startY, endY) in segments:
# construct a mask for each corner of the image, subtracting
# the elliptical center from it
cornerMask = np.zeros(image.shape[:2], dtype = "uint8")
cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
cornerMask = cv2.subtract(cornerMask, ellipMask)
# extract a color histogram from the image, then update the
# feature vector
hist = self.histogram(image, cornerMask)
features.extend(hist)
# extract a color histogram from the elliptical region and
# update the feature vector
hist = self.histogram(image, ellipMask)
features.extend(hist)
# return the feature vector
return features