本文整理匯總了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