本文整理匯總了Python中cv2.calcHist方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.calcHist方法的具體用法?Python cv2.calcHist怎麽用?Python cv2.calcHist使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.calcHist方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _update_mean_shift_bookkeeping
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def _update_mean_shift_bookkeeping(self, frame, box_grouped):
"""Preprocess all valid bounding boxes for mean-shift tracking
This method preprocesses all relevant bounding boxes (those that
have been detected by both mean-shift tracking and saliency) for
the next mean-shift step.
:param frame: current RGB input frame
:param box_grouped: list of bounding boxes
"""
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
self.object_roi = []
self.object_box = []
for box in box_grouped:
(x, y, w, h) = box
hsv_roi = hsv[y:y + h, x:x + w]
mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
np.array((180., 255., 255.)))
roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
self.object_roi.append(roi_hist)
self.object_box.append(box)
示例2: calculate_roi_hist
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def calculate_roi_hist(self, frame):
"""Calculates region of interest histogram.
Args:
frame: The np.array image frame to calculate ROI histogram for.
"""
(x, y, w, h) = self.box
roi = frame[y:y + h, x:x + w]
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
np.array((180., 255., 255.)))
roi_hist = cv2.calcHist([hsv_roi], [0, 1], mask, [180, 255],
[0, 180, 0, 255])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
self.roi_hist = roi_hist
# Run this every frame
示例3: capture_histogram
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def capture_histogram(path_of_sample):
# read the image
color = cv2.imread(path_of_sample)
# convert to HSV
color_hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)
# compute the histogram
object_hist = cv2.calcHist([color_hsv], # image
[0, 1], # channels
None, # no mask
[180, 256], # size of histogram
[0, 180, 0, 256] # channel values
)
# min max normalization
cv2.normalize(object_hist, object_hist, 0, 255, cv2.NORM_MINMAX)
return object_hist
開發者ID:PacktPublishing,項目名稱:Hands-On-Machine-Learning-with-OpenCV-4,代碼行數:22,代碼來源:object_detection_using_color.py
示例4: sort_hist
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def sort_hist(self):
""" Sort by image histogram similarity """
logger.info("Sorting by histogram similarity...")
filename_list, image_list = self._get_images()
distance = cv2.HISTCMP_BHATTACHARYYA
logger.info("Calculating histograms...")
histograms = [cv2.calcHist([img], [0], None, [256], [0, 256]) for img in image_list]
img_list = list(zip(filename_list, histograms))
logger.info("Comparing histograms and sorting...")
img_list_len = len(img_list)
for i in tqdm(range(0, img_list_len - 1), desc="Comparing", file=sys.stdout):
min_score = float("inf")
j_min_score = i + 1
for j in range(i + 1, img_list_len):
score = cv2.compareHist(img_list[i][1], img_list[j][1], distance)
if score < min_score:
min_score = score
j_min_score = j
(img_list[i + 1], img_list[j_min_score]) = (img_list[j_min_score], img_list[i + 1])
return img_list
示例5: sort_hist_dissim
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def sort_hist_dissim(self):
""" Sort by image histogram dissimilarity """
logger.info("Sorting by histogram dissimilarity...")
filename_list, image_list = self._get_images()
scores = np.zeros(len(filename_list), dtype='float32')
distance = cv2.HISTCMP_BHATTACHARYYA
logger.info("Calculating histograms...")
histograms = [cv2.calcHist([img], [0], None, [256], [0, 256]) for img in image_list]
img_list = list(list(items) for items in zip(filename_list, histograms, scores))
logger.info("Comparing histograms...")
img_list_len = len(img_list)
for i in tqdm(range(0, img_list_len), desc="Comparing", file=sys.stdout):
score_total = 0
for j in range(0, img_list_len):
if i == j:
continue
score_total += cv2.compareHist(img_list[i][1], img_list[j][1], distance)
img_list[i][2] = score_total
logger.info("Sorting...")
img_list = sorted(img_list, key=operator.itemgetter(2), reverse=True)
return img_list
示例6: get_foreground_background_probs
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def get_foreground_background_probs(frame,obj_rect,num_bins,bin_mapping=None):
frame=frame.astype(np.uint8)
surr_hist = cv2.calcHist([frame],[0, 1, 2], None, [num_bins,num_bins,num_bins],
[0, 256, 0, 256, 0, 256])
x,y,w,h=obj_rect
if x+w>frame.shape[1]-1:
w=(frame.shape[1]-1)-x
if y+h>frame.shape[0]-1:
h=(frame.shape[0]-1)-y
x=int(max(x,0))
y=int(max(y,0))
obj_win=frame[y:y+h+1,x:x+w+1]
obj_hist = cv2.calcHist([obj_win], [0, 1, 2], None, [num_bins, num_bins, num_bins], [0, 256, 0, 256, 0, 256])
prob_lut = (obj_hist + 1) / (surr_hist + 2)
prob_map = None
if bin_mapping is not None:
frame_bin = cv2.LUT(frame, bin_mapping).astype(np.int64)
prob_map = prob_lut[frame_bin[:, :, 0], frame_bin[:, :, 1], frame_bin[:, :, 2]]
return prob_lut,prob_map
示例7: addModelHistogram
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def addModelHistogram(self, model_frame, name=''):
"""Add the histogram to internal container. If the name of the object
is already present then replace that histogram with a new one.
@param model_frame the frame to add to the model, its histogram
is obtained and saved in internal list.
@param name a string representing the name of the model.
If nothing is specified then the name will be the index of the element.
"""
if(self.hist_type=='HSV'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2HSV)
elif(self.hist_type=='GRAY'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2GRAY)
elif(self.hist_type=='RGB'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2RGB)
hist = cv2.calcHist([model_frame], self.channels, None, self.hist_size, self.hist_range)
hist = cv2.normalize(hist, hist).flatten()
if name == '': name = str(len(self.model_list))
if name not in self.name_list:
self.model_list.append(hist)
self.name_list.append(name)
else:
for i in range(len(self.name_list)):
if self.name_list[i] == name:
self.model_list[i] = hist
break
示例8: returnHistogramComparisonArray
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def returnHistogramComparisonArray(self, image, method='intersection'):
"""Return the comparison array between all the model and the input image.
The highest value represents the best match.
@param image the image to compare
@param method the comparison method.
intersection: (default) the histogram intersection (Swain, Ballard)
@return a numpy array containg the comparison value between each pair image-model
"""
if(self.hist_type=='HSV'): image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
elif(self.hist_type=='GRAY'): image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
elif(self.hist_type=='RGB'): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
comparison_array = np.zeros(len(self.model_list))
image_hist = cv2.calcHist([image], self.channels, None, self.hist_size, self.hist_range)
image_hist = cv2.normalize(image_hist, image_hist).flatten()
counter = 0
for model_hist in self.model_list:
comparison_array[counter] = self.returnHistogramComparison(image_hist, model_hist, method=method)
counter += 1
return comparison_array
示例9: sort_by_hist_dissim
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def sort_by_hist_dissim(input_path):
io.log_info ("Sorting by histogram dissimilarity...")
img_list = []
trash_img_list = []
for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
filepath = Path(filepath)
dflimg = DFLIMG.load (filepath)
image = cv2_imread(str(filepath))
if dflimg is not None and dflimg.has_data():
face_mask = LandmarksProcessor.get_image_hull_mask (image.shape, dflimg.get_landmarks())
image = (image*face_mask).astype(np.uint8)
img_list.append ([str(filepath), cv2.calcHist([cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)], [0], None, [256], [0, 256]), 0 ])
img_list = HistDissimSubprocessor(img_list).run()
io.log_info ("Sorting...")
img_list = sorted(img_list, key=operator.itemgetter(2), reverse=True)
return img_list, trash_img_list
示例10: _equalize_pil
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def _equalize_pil(img, mask=None):
histogram = cv2.calcHist([img], [0], mask, [256], (0, 256)).ravel()
h = [_f for _f in histogram if _f]
if len(h) <= 1:
return img.copy()
step = np.sum(h[:-1]) // 255
if not step:
return img.copy()
lut = np.empty(256, dtype=np.uint8)
n = step // 2
for i in range(256):
lut[i] = min(n // step, 255)
n += histogram[i]
return cv2.LUT(img, np.array(lut))
示例11: describe
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def describe(self, image, mask):
image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
hist = cv.calcHist([image], [0, 1, 2], mask,
self.bins, [0, 256, 0, 256, 0, 256])
hist = hist / np.sum(hist)
# 512 dimensions
return hist.flatten()
開發者ID:JACKYLUO1991,項目名稱:Face-skin-hair-segmentaiton-and-skin-color-evaluation,代碼行數:10,代碼來源:cal_pca.py
示例12: describe
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def describe(self, image, mask):
hist_b = cv.calcHist([image], [0], mask, self.bins,
[0, 256])
hist_g = cv.calcHist([image], [1], mask, self.bins,
[0, 256])
hist_r = cv.calcHist([image], [2], mask, self.bins,
[0, 256])
hist_b = hist_b / np.sum(hist_b)
hist_g = hist_g / np.sum(hist_g)
hist_r = hist_r / np.sum(hist_r)
# 24 dimensions
return np.concatenate([hist_b, hist_g, hist_r], axis=0).reshape(-1)
開發者ID:JACKYLUO1991,項目名稱:Face-skin-hair-segmentaiton-and-skin-color-evaluation,代碼行數:15,代碼來源:cal_histogram.py
示例13: color_histogram_of_test_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def color_histogram_of_test_image(test_src_image):
# load the image
image = test_src_image
chans = cv2.split(image)
colors = ('b', 'g', 'r')
features = []
feature_data = ''
counter = 0
for (chan, color) in zip(chans, colors):
counter = counter + 1
hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
features.extend(hist)
# find the peak pixel values for R, G, and B
elem = np.argmax(hist)
if counter == 1:
blue = str(elem)
elif counter == 2:
green = str(elem)
elif counter == 3:
red = str(elem)
feature_data = red + ',' + green + ',' + blue
with open(current_path + '/utils/color_recognition_module/'
+ 'test.data', 'w') as myfile:
myfile.write(feature_data)
示例14: describe
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def describe(self, image, mask=None):
# Compute a 3D histogram in the RGB colorspace, then normalize the histogram so that images
# with the same content will have roughly the same histogram
hist = cv2.calcHist([image], [0, 1, 2], mask, self.bins, [0, 256, 0, 256, 0, 256])
cv2.normalize(hist, hist)
# Return the 3D histogram as a flattened array
return hist.flatten()
示例15: hand_capture
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import calcHist [as 別名]
def hand_capture(frame_in,box_x,box_y):
hsv = cv2.cvtColor(frame_in, cv2.COLOR_BGR2HSV)
ROI = np.zeros([capture_box_dim*capture_box_count,capture_box_dim,3], dtype=hsv.dtype)
for i in xrange(capture_box_count):
ROI[i*capture_box_dim:i*capture_box_dim+capture_box_dim,0:capture_box_dim] = hsv[box_y[i]:box_y[i]+capture_box_dim,box_x[i]:box_x[i]+capture_box_dim]
hand_hist = cv2.calcHist([ROI],[0, 1], None, [180, 256], [0, 180, 0, 256])
cv2.normalize(hand_hist,hand_hist, 0, 255, cv2.NORM_MINMAX)
return hand_hist
# 2. Filters and threshold