VideoCapture_read.py 使用ret=cap.set(3,320)和ret=cap.set(4,240) 来把宽和高改成320X240

# -*- coding: utf-8 -*-
"""
Created on Fri Jan 3 21:06:22 2014

@author: duan
"""

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

width=cap.get(3)
height=cap.get(4)
print width
print height

ret=cap.set(3,320)
ret=cap.set(4,240)
width=cap.get(3)
height=cap.get(4)
print width
print height

if cap.isOpened():
  while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret==True:
      # Our operations on the frame come here
      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

      # Display the resulting frame
      cv2.imshow('frame',gray)
    key=cv2.waitKey(1)
    if key & 0xFF == ord('q'):
     break
    elif key & 0xFF == ord('a'):
     ret=cap.set(3,640)
     ret=cap.set(4,480)
    elif key & 0xFF == ord('s'):
     ret=cap.set(3,320)
     ret=cap.set(4,240)
  # When everything done, release the capture
  cap.release()
  cv2.destroyAllWindows()
else:
  print 'cap is not Opened!'


你可以使用函数cap.get(propId) 来获得视频的一些参数信息。这里
propId 可以是0 到18 之间的任何整数。每一个数代表视频的一个属性,见
下表
其中的一些值可以使用cap.set(propId,value) 来修改,value 就是
你想要设置成的新值。
例如,我可以使用cap.get(3) 和cap.get(4) 来查看每一帧的宽和高。
默认情况下得到的值是640X480。但是我可以使用ret=cap.set(3,320)
和ret=cap.set(4,240) 来把宽和高改成320X240。


如果您想提取 YOLOv5 6.0 版本的 detect.py 中关于摄像头的代码,可以按照以下步骤进行: 1. 打开 detect.py 文件,找到以下代码: ```python # Camera inference elif source.isnumeric(): source = int(source) # Start streaming cap = cv2.VideoCapture(source) assert cap.isOpened(), f'Failed to open {source}' cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) fps = cap.get(cv2.CAP_PROP_FPS) print(f'Using {source} with FPS {fps:.3f} [OK]') for path, img, im0s, vid_cap in dataset: if vid_path != path: vid_path, frames = path, [] if isinstance(vid_cap, cv2.VideoCapture): frames = vid_cap.get(cv2.CAP_PROP_FRAME_COUNT) elif isinstance(vid_cap, int): frames = vid_cap else: assert False, f'Invalid video {path}' t1 = time_synchronized() # Get frames ret, frame = cap.read() if not ret: break assert frame is not None, 'Image Not Found ' # Padded resize frame = letterbox(frame, new_shape=inp_shape)[0] # Normalize RGB frame = frame[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 frame = np.ascontiguousarray(frame) # Inference img = torch.from_numpy(frame).to(device) img = img.half() if half else img.float() # uint8 to fp16/32 img /= 255.0 # 0 - 255 to 0.0 - 1.0 if img.ndimension() == 3: img = img.unsqueeze(0) # Inference t2 = time_synchronized() pred = model(img, augment=opt.augment)[0] # Apply NMS pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) t3 = time_synchronized() # Process detections for i, det in enumerate(pred): # detections per image p, s, im0 = path, '', im0s.copy() gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh if det is not None and len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, -1].unique(): n = (det[:, -1] == c).sum() # detections per class s += f'{n} {names[int(c)]}s, ' # add to string # Write results for *xyxy, conf, cls in det: if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh with open(txt_path + '.txt', 'a') as f: f.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format if save_img or save_crop or save_patch: # Add bbox to image c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=3, **plot_kwargs) if save_crop or save_patch: # Save crop #crop = im0[int(xyxy[1]):int(xyxy[3]), int(xyxy[0]):int(xyxy[2])] save_file = str(Path(save_dir) / Path(p).stem) + f'_{i}_{names[c]}.jpg' cv2.imwrite(save_file, crop) # Print results print(f'{s}Done. ({t3 - t1:.3f}s)') # Stream results if view_img: cv2.imshow(p, im0) if cv2.waitKey(1) == ord('q'): # q to quit raise StopIteration if save_txt or save_img: print(f"Results saved to {save_dir}") if platform == 'darwin': # MacOS os.system(f'open {save_dir}') cap.release() ``` 2. 将以上代码复制到一个新文件中 3. 删除以下代码: ```python elif source.isnumeric(): source = int(source) # Start streaming cap = cv2.VideoCapture(source) assert cap.isOpened(), f'Failed to open {source}' cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) fps = cap.get(cv2.CAP_PROP_FPS) print(f'Using {source} with FPS {fps:.3f} [OK]') ``` 4. 将下面的代码留下来: ```python for path, img, im0s, vid_cap in dataset: if vid_path != path: vid_path, frames = path, [] if isinstance(vid_cap, cv2.VideoCapture): frames = vid_cap.get(cv2.CAP_PROP_FRAME_COUNT) elif isinstance(vid_cap, int): frames = vid_cap else: assert False, f'Invalid video {path}' t1 = time_synchronized() # Get frames ret, frame = cap.read() if not ret: break assert frame is not None, 'Image Not Found ' # Padded resize frame = letterbox(frame, new_shape=inp_shape)[0] # Normalize RGB frame = frame[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 frame = np.ascontiguousarray(frame) # Inference img = torch.from_numpy(frame).to(device) img = img.half() if half else img.float() # uint8 to fp16/32 img /= 255.0 # 0 - 255 to 0.0 - 1.0 if img.ndimension() == 3: img = img.unsqueeze(0) # Inference t2 = time_synchronized() pred = model(img, augment=opt.augment)[0] # Apply NMS pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) t3 = time_synchronized() # Process detections for i, det in enumerate(pred): # detections per image p, s, im0 = path, '', im0s.copy() gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh if det is not None and len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, -1].unique(): n = (det[:, -1] == c).sum() # detections per class s += f'{n} {names[int(c)]}s, ' # add to string # Write results for *xyxy, conf, cls in det: if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh with open(txt_path + '.txt', 'a') as f: f.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format if save_img or save_crop or save_patch: # Add bbox to image c = int(cls) # integer class label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=3, **plot_kwargs) if save_crop or save_patch: # Save crop #crop = im0[int(xyxy[1]):int(xyxy[3]), int(xyxy[0]):int(xyxy[2])] save_file = str(Path(save_dir) / Path(p).stem) + f'_{i}_{names[c]}.jpg' cv2.imwrite(save_file, crop) # Print results print(f'{s}Done. ({t3 - t1:.3f}s)') # Stream results if view_img: cv2.imshow(p, im0) if cv2.waitKey(1) == ord('q'): # q to quit raise StopIteration ``` 这部分代码处理摄像头输入并进行推理。 5. 将提取出的代码保存到一个新文件中,例如 camera_detect.py。 现在您可以使用 camera_detect.py 进行摄像头推理。请确保在运行代码之前正确设置 YOLOv5 模型、类别和权重路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值