def compute(self, frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
descriptor = []
dominantGradients = np.zeros_like(frame)
maxGradient = cv2.filter2D(frame, cv2.CV_32F, self.kernels[0])
maxGradient = np.absolute(maxGradient)
for k in range(1,len(self.kernels)):
kernel = self.kernels[k]
gradient = cv2.filter2D(frame, cv2.CV_32F, kernel)
gradient = np.absolute(gradient)
np.maximum(maxGradient, gradient, maxGradient)
indices = (maxGradient == gradient)
dominantGradients[indices] = k
frameH, frameW = frame.shape
for row in range(self.rows):
for col in range(self.cols):
mask = np.zeros_like(frame)
mask[((frameH/self.rows)*row):((frameH/self.rows)*(row+1)),(frameW/self.cols)*col:((frameW/self.cols)*(col+1))] = 255
hist = cv2.calcHist([dominantGradients], [0], mask, self.bins, self.range)
hist = cv2.normalize(hist, None)
descriptor.append(hist)
return np.concatenate([x for x in descriptor])
python类calcHist()的实例源码
def compute(self, frame):
#frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
dx = cv2.filter2D(frame, cv2.CV_32F, self.xkernel)
dy = cv2.filter2D(frame, cv2.CV_32F, self.ykernel)
orientations = np.zeros_like(dx)
magnitudes = np.zeros_like(dx)
cv2.cartToPolar(dx,dy, magnitudes,orientations)
descriptor = []
frameH, frameW = frame.shape
mask_threshold = magnitudes <= self.threshold
for row in range(self.rows):
for col in range(self.cols):
mask = np.zeros_like(frame)
mask[((frameH/self.rows)*row):((frameH/self.rows)*(row+1)),(frameW/self.cols)*col:((frameW/self.cols)*(col+1))] = 1
mask[mask_threshold] = 0
a_, b_ = mask.shape
hist = cv2.calcHist([orientations], self.channel, mask, [self.bins], self.range)
hist = cv2.normalize(hist, None)
descriptor.append(hist)
return np.concatenate([x for x in descriptor])
def calculate_entropy(image):
entropy = image.copy()
sum = 0
i = 0
j = 0
while i < entropy.shape[0]:
j = 0
while j < entropy.shape[1]:
sub_image = entropy[i:i+10,j:j+10]
histogram = cv2.calcHist([sub_image],[0],None,[256],[0,256])
sum = 0
for k in range(256):
if histogram[k] != 0:
sum = sum + (histogram[k] * math.log(histogram[k]))
k = k + 1
entropy[i:i+10,j:j+10] = sum
j = j+10
i = i+10
ret2,th2 = cv2.threshold(entropy,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
newfin = cv2.erode(th2, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
return newfin
def leftRightHistEqualize(self, img_left, img_right) :
lookup = np.zeros([256], np.uint8)
cdf_new = np.zeros([256])
rows,cols = img_right.shape
img_left_new = np.zeros([rows,cols], np.uint8)
hist_left = cv2.calcHist([img_left],[0],None,[256],[0,255])
hist_right = cv2.calcHist([img_right],[0],None,[256],[0,255])
cdf_left_norm = hist_left.cumsum() /(rows*cols)
cdf_right_norm = hist_right.cumsum() /(rows*cols)
for i in range(0,256):
lookup[i] = np.argmin(np.abs(cdf_left_norm[i]-cdf_right_norm))
# cdf_new[i] = cdf_right_norm[lookup[i]]
img_left_new[ np.where(img_left==i) ] = lookup[i]
return img_left_new
def gimpMarkup(self, hints = gimpContours, image = "2x2-red-1.jpg", feature = "top-left-monitor"):
r = Rectangle(*hints[image][feature])
contour = r.asContour()
cv2.drawContours(self.img, [contour], -1, (0, 255, 0), 5 )
title = self.tgen.next(feature)
if self.show: ImageViewer(self.img).show(window=title, destroy = self.destroy, info = self.info, thumbnailfn = title)
roi = r.getRoi(self.img)
self.rois[feature] = roi
# Histogram the ROI to get the spread of intensities, in each channel and grayscale
title = '%s-roi.jpg' % feature
if self.show: ImageViewer(roi).show(window=title, destroy = self.destroy, info = self.info, thumbnailfn = title)
colors = ('b','g','r')
for i,col in enumerate(colors):
hist = cv2.calcHist([roi], [i], None, [256], [0,256])
plt.plot(hist, color = col)
plt.xlim([0,256])
#plt.hist(roi.ravel(), 256, [0,256])
plt.show()
cmap = ColorMapper(roi)
cmap.mapit(1)
title = self.tgen.next('colourMapping')
if self.show: ImageViewer(self.img).show(window=title, destroy = self.destroy, info = self.info, thumbnailfn = title)
cv2.waitKey()
def describe(self, image):
# Compute a 3D histogram in the RGB colorspace and normalize.
hist = cv2.calcHist([image], [0, 1, 2],
None, self.bins, [0, 256, 0, 256, 0, 256])
hist = cv2.normalize(hist, hist)
# Return the 3D histogram output as a flattened array.
return hist.flatten()
def calculate_entropy(image):
entropy = image.copy()
sum = 0
i = 0
j = 0
while i < entropy.shape[0]:
j = 0
while j < entropy.shape[1]:
sub_image = entropy[i:i+10,j:j+10]
histogram = cv2.calcHist([sub_image],[0],None,[256],[0,256])
sum = 0
for k in range(256):
if histogram[k] != 0:
sum = sum + (histogram[k] * math.log(histogram[k]))
k = k + 1
entropy[i:i+10,j:j+10] = sum
j = j+10
i = i+10
ret2,th2 = cv2.threshold(entropy,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
newfin = cv2.erode(th2, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
return newfin
def accumulated_histogram(images, args):
histogram = args[0]
try:
image, x, y = images.get(timeout=0.3)
except:
return
hsv = cv2.cvtColor(np.array(image, dtype=np.uint8), cv2.COLOR_RGB2HSV)
current_histogram = histogram.get()
new_histogram = list(map(lambda x: cv2.calcHist([hsv[:,:,x]],
[0],
None,
[256],
[0, 256],
hist=current_histogram[x],
accumulate=True),
range(3)))
histogram.put(new_histogram)
images.task_done()
def extract_color_histogram(image, bins=(8, 8, 8)):
# extract a 3D color histogram from the HSV color space using
# the supplied number of `bins` per channel
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0, 1, 2], None, bins, [0, 180, 0, 256, 0, 256])
# handle normalizing the histogram if we are using OpenCV 2.4.X
if imutils.is_cv2():
hist = cv2.normalize(hist)
# otherwise, perform "in place" normalization in OpenCV 3 (I
# personally hate the way this is done
else:
cv2.normalize(hist, hist)
# return the flattened histogram as the feature vector
return hist.flatten()
def main():
target_im = cv2.imread(sys.argv[1])
target_hist = cv2.calcHist([target_im], [0], None, [256], [0, 256])
for i in list:
comparing_im = cv2.imread(i)
comparing_hist = cv2.calcHist([comparing_im], [0], None, [256], [0, 256])
diff = cv2.compareHist(target_hist, comparing_hist, 0)
if diff > float(sys.argv[2]):
print i,
print diff
def compute(self, frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frameH, frameW = frame.shape
descriptor = []
for row in range(self.rows):
for col in range(self.cols):
mask = np.zeros_like(frame)
mask[((frameH/self.rows)*row):((frameH/self.rows)*(row+1)),(frameW/self.cols)*col:((frameW/self.cols)*(col+1))] = 1
hist = cv2.calcHist([frame], self.channel, mask, [self.bins], self.range)
hist = cv2.normalize(hist, None)
descriptor.append(hist)
return np.concatenate([x for x in descriptor])
def test_features():
from atx.drivers.android_minicap import AndroidDeviceMinicap
cv2.namedWindow("preview")
d = AndroidDeviceMinicap()
# r, h, c, w = 200, 100, 200, 100
# track_window = (c, r, w, h)
# oldimg = cv2.imread('base1.png')
# roi = oldimg[r:r+h, c:c+w]
# hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
# mask = cv2.inRange(hsv_roi, 0, 255)
# roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0,180])
# cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
# term_cirt = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
while True:
try:
w, h = d._screen.shape[:2]
img = cv2.resize(d._screen, (h/2, w/2))
cv2.imshow('preview', img)
hist = cv2.calcHist([img], [0], None, [256], [0,256])
plt.plot(plt.hist(hist.ravel(), 256))
plt.show()
# if img.shape == oldimg.shape:
# # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# # ret, track_window = cv2.meanShift(hsv, track_window, term_cirt)
# # x, y, w, h = track_window
# cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
# cv2.imshow('preview', img)
# # cv2.imshow('preview', img)
cv2.waitKey(1)
except KeyboardInterrupt:
break
cv2.destroyWindow('preview')
def _classify_partition(self, partition):
"""Classifies a partition.
Args:
partition: Partition.
Returns:
GameMapObjects enum.
"""
histogram = cv2.calcHist([partition], [0], None, [256], [0, 256])
return self._classify_histogram(histogram)
def describe(image, mask = None):
hist = cv2.calcHist([image], [0, 1, 2], mask, [8,8,8], [0, 256, 0, 256, 0, 256])
cv2.normalize(hist, hist)
return hist.flatten()
def describe(image, mask = None):
hist = cv2.calcHist([image], [0, 1, 2], mask, [8,8,8], [0, 256, 0, 256, 0, 256])
cv2.normalize(hist, hist)
return hist.flatten()
def test_features():
from atx.drivers.android_minicap import AndroidDeviceMinicap
cv2.namedWindow("preview")
d = AndroidDeviceMinicap()
# r, h, c, w = 200, 100, 200, 100
# track_window = (c, r, w, h)
# oldimg = cv2.imread('base1.png')
# roi = oldimg[r:r+h, c:c+w]
# hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
# mask = cv2.inRange(hsv_roi, 0, 255)
# roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0,180])
# cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
# term_cirt = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
while True:
try:
w, h = d._screen.shape[:2]
img = cv2.resize(d._screen, (h/2, w/2))
cv2.imshow('preview', img)
hist = cv2.calcHist([img], [0], None, [256], [0,256])
plt.plot(plt.hist(hist.ravel(), 256))
plt.show()
# if img.shape == oldimg.shape:
# # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# # ret, track_window = cv2.meanShift(hsv, track_window, term_cirt)
# # x, y, w, h = track_window
# cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
# cv2.imshow('preview', img)
# # cv2.imshow('preview', img)
cv2.waitKey(1)
except KeyboardInterrupt:
break
cv2.destroyWindow('preview')
def accumulated_histogram(image, histogram):
hist = list(map(lambda x: cv2.calcHist([image],
[x],
None,
[256],
[0, 256]),
range(3)))
for x in range(3):
histogram[x] = np.add(hist[x].ravel(), histogram[x].ravel())
return histogram
def run(self, video_path=None):
if video_path is not None:
self.video_path = video_path
assert (self.video_path is not None), "you should must the video path!"
self.shots = []
self.scores = []
self.frames = []
hists = []
cap = cv2.VideoCapture(self.video_path)
self.frame_count = cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
self.fps = cap.get(cv2.cv.CV_CAP_PROP_FPS)
while True:
success, frame = cap.read()
if not success:
break
self.frames.append(frame)
# millis = cap.get(cv2.cv.CV_CAP_PROP_POS_MSEC)
# print millis
# compute RGB histogram for each frame
chists = [cv2.calcHist([frame], [c], None, [__hist_size__], [0,256]) \
for c in range(3)]
chists = np.array([chist for chist in chists])
hists.append(chists.flatten())
# compute hist distances
self.scores = [np.ndarray.sum(abs(pair[0] - pair[1])) for pair in zip(hists[1:], hists[:-1])]
add_steering_wheel_to_replay_memory.py 文件源码
项目:self-driving-truck
作者: aleju
项目源码
文件源码
阅读 52
收藏 0
点赞 0
评论 0
def screens_show_same_scene(scr1, scr2):
scr1 = ia.imresize_single_image(scr1, (50, 70))
scr2 = ia.imresize_single_image(scr2, (50, 70))
hist1 = cv2.calcHist([scr1[...,0], scr1[...,1], scr1[...,2]], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
hist2 = cv2.calcHist([scr2[...,0], scr2[...,1], scr2[...,2]], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
diff = np.sum(np.abs(hist1 - hist2))
return diff <= MAX_PIXELDIFF
HandRecognition.py 文件源码
项目:hand-gesture-recognition-opencv
作者: mahaveerverma
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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
def getLBP(img):
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
radius = 1
n_points = 8 * radius
lbpImage = (local_binary_pattern(img2, n_points, radius)).astype(int)**(1.0/radius)
# block processing:
lbpImages = block_view(lbpImage, ( int(lbpImage.shape[0] / 2), int(lbpImage.shape[1] / 4)))
count = 0
LBP = np.array([]);
for i in range(lbpImages.shape[0]): # for each block:
for j in range(lbpImages.shape[1]):
count += 1
# plt.subplot(4,2,count)
# plt.imshow(lbpImages[i,j,:,:],cmap = cm.Greys_r)
# plt.subplot(4,2,count+4*2/2)
# print count*2+1
LBPt = cv2.calcHist([lbpImages[i,j,:,:].astype('uint8')], [0], None, [8], [0, 256])
LBP = np.append(LBP, LBPt[:,0]);
# plt.plot(LBPt)
# plt.show()
Fnames = ["LBP"+str(i).zfill(2) for i in range(len(LBP))]
return normalize(LBP).tolist(), Fnames
def getRGBS(img, PLOT = False):
image = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# grab the image channels, initialize the tuple of colors,
# the figure and the flattened feature vector
features = []
featuresSobel = []
Grayscale = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY)
histG = cv2.calcHist([Grayscale], [0], None, [16], [0, 256])
histG = histG / histG.sum()
features.extend(histG[:,0].tolist())
grad_x = np.abs(cv2.Sobel(Grayscale, cv2.CV_16S, 1, 0, ksize = 3, scale = 1, delta = 0, borderType = cv2.BORDER_DEFAULT))
grad_y = np.abs(cv2.Sobel(Grayscale, cv2.CV_16S, 0, 1, ksize = 3, scale = 1, delta = 0, borderType = cv2.BORDER_DEFAULT))
abs_grad_x = cv2.convertScaleAbs(grad_x)
abs_grad_y = cv2.convertScaleAbs(grad_y)
dst = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0)
histSobel = cv2.calcHist([dst], [0], None, [16], [0, 256])
histSobel = histSobel / histSobel.sum()
features.extend(histSobel[:,0].tolist())
Fnames = []
Fnames.extend(["Color-Gray"+str(i) for i in range(8)])
Fnames.extend(["Color-GraySobel"+str(i) for i in range(8)])
return features, Fnames
def are_similar(self, first, second):
res = cv2.absdiff(first, second)
hist = cv2.calcHist([res], [0], None, [256], [0, 256])
return 1 - np.sum(hist[15::]) / np.sum(hist)
def are_similar(self, first, second):
result = 0
for i in xrange(3):
hist1 = cv2.calcHist([first], [i], None, [256], [0,256])
hist2 = cv2.calcHist([second], [i], None, [256], [0,256])
result += cv2.compareHist(hist1, hist2, self.get_technique())
return result / 3
def compute_hist(im):
hist = cv2.calcHist([im], [0, 1, 2], None, [8, 8, 8],
[0, 256, 0, 256, 0, 256])
hist = cv2.normalize(hist).flatten()
return hist
def __init__(self,frame,rect,method='m'):
r,c,h,w=rect
roi = frame[r:r+h, c:c+w]
mask = cv2.inRange(roi, np.array((0.)), np.array((255.)))
roi_hist = cv2.calcHist([roi],[0],mask,[16],[0,255])
roi_hist=cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
plotRects(frame,[rect])
cv2.waitKey(0)
cv2.destroyAllWindows()
self.roi_hist=roi_hist
self.track_window=tuple(rect)
self.m=method
self.frame=frame
def calHist(frame,rect):
r,c,h,w=rect
roi = frame[r:r+h, c:c+w]
mask = cv2.inRange(roi, np.array((0.)), np.array((255.)))
roi_hist = cv2.calcHist([roi],[0],mask,[255],[0,255])
roi_hist=cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
return roi_hist
def plot_histogram(image, title, mask=None):
chans = cv2.split(image)
colors = ("b", "g", "r")
plt.figure()
plt.title(title)
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
for (chan, color) in zip(chans, colors):
hist = cv2.calcHist([chan], [0], mask, [256], [0, 256])
plt.plot(hist, color=color)
plt.xlim([0, 256])
plt.show()
# Parse the command line arguments
def hist_lines(image, start, end):
scale = 4
height = 1080
result = np.zeros((height, 256 * scale, 1))
hist = cv2.calcHist([image], [0], None, [256], [start, end])
cv2.normalize(hist, hist, 0, height, cv2.NORM_MINMAX)
hist = np.int32(np.around(hist))
for x, y in enumerate(hist):
cv2.rectangle(result, (x * scale, 0), ((x + 1) * scale, y), (255), -1)
result = np.flipud(result)
return result
def extract(img):
return np.ravel(cv2.calcHist([img],[2],None,[126],[0,256]))