本文整理汇总了Python中cv2.cvtColor方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.cvtColor方法的具体用法?Python cv2.cvtColor怎么用?Python cv2.cvtColor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.cvtColor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def main():
imagePath = "img.jpg"
img = cv2.imread(imagePath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
generate_histogram(gray)
cv2.imwrite("before.jpg", gray)
gray = cv2.equalizeHist(gray)
generate_histogram(gray)
cv2.imwrite("after.jpg",gray)
return 0
示例2: __get_annotation__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def __get_annotation__(self, mask, image=None):
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
segmentation = []
for contour in contours:
# Valid polygons have >= 6 coordinates (3 points)
if contour.size >= 6:
segmentation.append(contour.flatten().tolist())
RLEs = cocomask.frPyObjects(segmentation, mask.shape[0], mask.shape[1])
RLE = cocomask.merge(RLEs)
# RLE = cocomask.encode(np.asfortranarray(mask))
area = cocomask.area(RLE)
[x, y, w, h] = cv2.boundingRect(mask)
if image is not None:
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.drawContours(image, contours, -1, (0,255,0), 1)
cv2.rectangle(image,(x,y),(x+w,y+h), (255,0,0), 2)
cv2.imshow("", image)
cv2.waitKey(1)
return segmentation, [x, y, w, h], area
示例3: worker
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def worker(input_q, output_q):
# Load a (frozen) Tensorflow model into memory.
fps = FPS().start()
while True:
myprint("updata start ", time.time())
fps.update()
myprint("updata end ", time.time())
# global lock
# if lock.acquire():
# lock.release()
frame = input_q.get()
myprint("out queue {} and input que size {} after input_q get".format(output_q.qsize(), input_q.qsize()), time.time())
myprint("out queue {} and input que size {} after lock release ".format(output_q.qsize(), input_q.qsize()), time.time())
myprint("face process start", time.time())
# frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out_frame = face_process(frame)
myprint("out queue {} and input que size {}".format(output_q.qsize(), input_q.qsize()), time.time())
output_q.put(out_frame)
myprint("out queue {} and input que size {} ".format(output_q.qsize(), input_q.qsize()), time.time())
fps.stop()
示例4: augment_hsv
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
x = (np.random.uniform(-1, 1, 3) * np.array([hgain, sgain, vgain]) + 1).astype(np.float32) # random gains
img_hsv = (cv2.cvtColor(img, cv2.COLOR_BGR2HSV) * x.reshape((1, 1, 3))).clip(None, 255).astype(np.uint8)
cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
# def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5): # original version
# # SV augmentation by 50%
# img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # hue, sat, val
#
# S = img_hsv[:, :, 1].astype(np.float32) # saturation
# V = img_hsv[:, :, 2].astype(np.float32) # value
#
# a = random.uniform(-1, 1) * sgain + 1
# b = random.uniform(-1, 1) * vgain + 1
# S *= a
# V *= b
#
# img_hsv[:, :, 1] = S if a < 1 else S.clip(None, 255)
# img_hsv[:, :, 2] = V if b < 1 else V.clip(None, 255)
# cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
示例5: __getitem__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def __getitem__(self, index, to_tensor=True):
fn = self.image_fns[index]
img = cv2.cvtColor(cv2.imread(fn, 1), cv2.COLOR_BGR2RGB)
img, pad_top, pad_left = KuzushijiDataset.pad_to_ratio(img, ratio=1.5)
h, w = img.shape[:2]
# print(h / w, pad_left, pad_top)
assert img.ndim == 3
scaled_imgs = []
for scale in self.scales:
h_scale = int(scale * self.height)
w_scale = int(scale * self.width)
simg = cv2.resize(img, (w_scale, h_scale))
if to_tensor:
assert simg.ndim == 3, simg.ndim
simg = simg.transpose((2, 0, 1))
simg = th.from_numpy(simg.copy())
scaled_imgs.append(simg)
return scaled_imgs + [fn]
示例6: _update_mean_shift_bookkeeping
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [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)
示例7: ProcessFrame
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def ProcessFrame(self, frame):
# segment arm region
segment = self.SegmentArm(frame)
# make a copy of the segmented image to draw on
draw = cv2.cvtColor(segment, cv2.COLOR_GRAY2RGB)
# draw some helpers for correctly placing hand
cv2.circle(draw,(self.imgWidth/2,self.imgHeight/2),3,[255,102,0],2)
cv2.rectangle(draw, (self.imgWidth/3,self.imgHeight/3), (self.imgWidth*2/3, self.imgHeight*2/3), [255,102,0],2)
# find the hull of the segmented area, and based on that find the
# convexity defects
[contours,defects] = self.FindHullDefects(segment)
# detect the number of fingers depending on the contours and convexity defects
# draw defects that belong to fingers green, others red
[nofingers,draw] = self.DetectNumberFingers(contours, defects, draw)
# print number of fingers on image
cv2.putText(draw, str(nofingers), (30,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255))
return draw
示例8: to_tensor
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def to_tensor(pic):
"""Convert a ``numpy.ndarray`` image to tensor.
See ``ToTensor`` for more details.
Args:
pic (numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
if _is_numpy_image(pic):
if pic.ndim == 2:
pic = cv2.cvtColor(pic, cv2.COLOR_GRAY2RGB)
img = torch.from_numpy(pic.transpose((2, 0, 1)))
# backward compatibility
if isinstance(img, torch.ByteTensor):
return img.float().div(255)
else:
return img
else:
raise TypeError('pic should be ndarray. Got {}.'.format(type(pic)))
示例9: adjust_contrast
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def adjust_contrast(img, contrast_factor):
"""Adjust contrast of an Image.
Args:
img (CV Image): CV Image to be adjusted.
contrast_factor (float): How much to adjust the contrast. Can be any
non negative number. 0 gives a solid gray image, 1 gives the
original image while 2 increases the contrast by a factor of 2.
Returns:
CV Image: Contrast adjusted image.
"""
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.float32)
mean = round(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY).mean())
im = (1 - contrast_factor) * mean + contrast_factor * im
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
示例10: adjust_saturation
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def adjust_saturation(img, saturation_factor):
"""Adjust color saturation of an image.
Args:
img (CV Image): CV Image to be adjusted.
saturation_factor (float): How much to adjust the saturation. 0 will
give a black and white image, 1 will give the original image while
2 will enhance the saturation by a factor of 2.
Returns:
CV Image: Saturation adjusted image.
"""
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.float32)
degenerate = cv2.cvtColor(
cv2.cvtColor(
im,
cv2.COLOR_RGB2GRAY),
cv2.COLOR_GRAY2RGB)
im = (1 - saturation_factor) * degenerate + saturation_factor * im
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
示例11: worker
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def worker(input_q, output_q):
# Load a (frozen) Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
sess = tf.Session(graph=detection_graph)
fps = FPS().start()
while True:
fps.update()
frame = input_q.get()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
output_q.put(detect_objects(frame_rgb, sess, detection_graph))
fps.stop()
sess.close()
示例12: draw_outputs
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def draw_outputs(img, outputs, class_names=None):
boxes, objectness, classes = outputs
#boxes, objectness, classes = boxes[0], objectness[0], classes[0]
wh = np.flip(img.shape[0:2])
if img.ndim == 2 or img.shape[2] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
min_wh = np.amin(wh)
if min_wh <= 100:
font_size = 0.5
else:
font_size = 1
for i in range(classes.shape[0]):
x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
img = cv2.putText(img, '{}'.format(int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
(0, 0, 255), 1)
return img
示例13: draw_labels
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def draw_labels(x, y, class_names=None):
img = x.numpy()
if img.ndim == 2 or img.shape[2] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
boxes, classes = tf.split(y, (4, 1), axis=-1)
classes = classes[..., 0]
wh = np.flip(img.shape[0:2])
min_wh = np.amin(wh)
if min_wh <= 100:
font_size = 0.5
else:
font_size = 1
for i in range(len(boxes)):
x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
if class_names:
img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
(0, 0, 255), 1)
else:
img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
return img
示例14: _augment
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def _augment(self, img, r):
old_dtype = img.dtype
if img.ndim == 3:
if self.rgb is not None:
m = cv2.COLOR_RGB2GRAY if self.rgb else cv2.COLOR_BGR2GRAY
grey = cv2.cvtColor(img.astype('float32'), m)
mean = np.mean(grey)
else:
mean = np.mean(img, axis=(0, 1), keepdims=True)
else:
mean = np.mean(img)
img = img * r + mean * (1 - r)
if self.clip or old_dtype == np.uint8:
img = np.clip(img, 0, 255)
return img.astype(old_dtype)
示例15: getPeakFeatures
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import cvtColor [as 别名]
def getPeakFeatures():
net = DecafNet()
features = numpy.zeros((number_sequences,feature_length))
labels = numpy.zeros((number_sequences,1))
counter = 0
# Maybe sort them
for participant in os.listdir(os.path.join(data_dir,image_dir)):
for sequence in os.listdir(os.path.join(data_dir,image_dir, participant)):
if sequence != ".DS_Store":
image_files = sorted(os.listdir(os.path.join(data_dir,image_dir, participant,sequence)))
image_file = image_files[-1]
print counter, image_file
imarray = cv2.imread(os.path.join(data_dir,image_dir, participant,sequence,image_file))
imarray = cv2.cvtColor(imarray,cv2.COLOR_BGR2GRAY)
scores = net.classify(imarray, center_only=True)
features[counter] = net.feature(feature_level)#.flatten()
label_file = open(os.path.join(data_dir,label_dir, participant,sequence,image_file[:-4]+"_emotion.txt"))
labels[counter] = eval(label_file.read())
label_file.close()
counter += 1
numpy.save("featuresPeak5",features)
numpy.save("labelsPeak5",labels)