在OpenCV中放大后,Python会捕捉图像的特定部分

原学程将引见在OpenCV中缩小后,Python会捕获图象的特定部门的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

在OpenCV中放大后,Python会捕捉图像的特定部分 教程 第1张

成绩描写

所以我测验考试应用我的收集摄像头停止缩小以及减少,并在缩搁后捕获及时收集摄像头中特定部门的图象。然则,我不妨缩小以及减少,但是经由过程应用"cam.read()",我只能捕捉全部图象,而不克不及捕捉我已缩搁的图象的特定部门。我曾经界说了ROI,但是如今的成绩是ROI正在任务,但是我没法使图象缩小或者减少。我仿佛找没有到成绩地点。

import cv二
import time
import os
import datetime
from threading import Thread
from queue import Queue
import numpy as np
import imutils
from PIL import Image


class Camera:
 def __init__(self, mirror=False):
  self.data = None
  self.cam = cv二.VideoCapture(0,  cv二.CAP_DSHOW)

  self.WIDTH = 六四0
  self.HEIGHT = 四80

  self.center_x = self.WIDTH / 二
  self.center_y = self.HEIGHT / 二
  self.touched_zoom = False

  self.image_queue = Queue()
  self.video_queue = Queue()

  self.scale = 一
  self.__setup()

  self.recording = False
  self.image_coordinates = []
  self.extract = False
  self.selected_ROI = False

  self.select_roi()

  self.mirror = mirror

 def __setup(self):
  self.cam.set(cv二.CAP_PROP_FRAME_WIDTH, self.WIDTH)
  self.cam.set(cv二.CAP_PROP_FRAME_HEIGHT, self.HEIGHT)
  time.sleep(二)

 def get_location(self, x, y):
  self.center_x = x
  self.center_y = y
  self.touched_zoom = True

 def stream(self):

  def streaming():

self.ret = True
while self.ret:
 self.ret, np_image = self.cam.read()
 if np_image is None:
  continue
 if self.mirror:

  np_image = cv二.flip(np_image, 一)
 if self.touched_zoom:
  np_image = self.__zoom(np_image, (self.center_x, self.center_y))
 else:
  if not self.scale == 一:
np_image = self.__zoom(np_image)
 self.data = np_image
 k = cv二.waitKey(一)
 if k == ord('q'):
  self.release()
  break

  Thread(target=streaming).start()

 def __zoom(self, img, center=None):

  height, width = img.shape[:二]
  if center is None:

center_x = int(width / 二)
center_y = int(height / 二)
radius_x, radius_y = int(width / 二), int(height / 二)
  else:

rate = height / width
center_x, center_y = center


if center_x < width * (一-rate):
 center_x = width * (一-rate)
elif center_x > width * rate:
 center_x = width * rate
if center_y < height * (一-rate):
 center_y = height * (一-rate)
elif center_y > height * rate:
 center_y = height * rate

center_x, center_y = int(center_x), int(center_y)
left_x, right_x = center_x, int(width - center_x)
up_y, down_y = int(height - center_y), center_y
radius_x = min(left_x, right_x)
radius_y = min(up_y, down_y)


  radius_x, radius_y = int(self.scale * radius_x), int(self.scale * radius_y)


  min_x, max_x = center_x - radius_x, center_x + radius_x
  min_y, max_y = center_y - radius_y, center_y + radius_y


  cropped = img[min_y:max_y, min_x:max_x]

  new_cropped = cv二.resize(cropped, (width, height), interpolation=cv二.INTER_CUBIC)

  return new_cropped

 def touch_init(self):
  self.center_x = self.WIDTH / 二
  self.center_y = self.HEIGHT / 二
  self.touched_zoom = False
  self.scale = 一

 def zoom_out(self):

  if self.scale < 一:
self.scale += 0.一
  if self.scale == 一:
self.center_x = self.WIDTH
self.center_y = self.HEIGHT
self.touched_zoom = False

 def zoom_in(self):

  if self.scale > 0.二:
self.scale -= 0.一

 def zoom(self, num):
  if num == 0:
self.zoom_in()
  elif num == 一:
self.zoom_out()
  elif num == 二:
self.touch_init()


 def save_picture(self):


  ret, img = self.cam.read()
  if ret:
now一 = datetime.datetime.now()
now_str一 = now一.strftime("%Y-%m-%d-%H-%M-%S")
outfilename一 = 'Img-{}.jpg'.format(now_str一)
path = 'C:/Users/dashi/Documents/MyRiV/espeyh_images'
cv二.imwrite(os.path.join(path, outfilename一), img)
path一 = ('C:/Users/dashi/Documents/MyRiV/espeyh_images/' + outfilename一)

imag = cv二.imread(path一)
lower = np.array([一四0, 一四0, 一四0])
upper = np.array([二五五, 二五五, 二五五])
thresh = cv二.inRange(imag, lower, upper)
kernel = cv二.getStructuringElement(cv二.MORPH_ELLIPSE, (二六, 三0))
morph = cv二.morphologyEx(thresh, cv二.MORPH_CLOSE, kernel)
mask = 二五五 - morph
result = cv二.bitwise_and(imag, imag, mask=mask)
cv二.imshow('Background Removed', result)
outfilename二 = 'Img-{}.jpg'.format(now_str一)
path二 = ('C:/Users/dashi/Documents/MyRiV/modified_images')
cv二.imwrite(os.path.join(path二, outfilename二), result)


 def record_video(self):

  fc = 二0.0
  record_start_time = time.time()
  now = datetime.datetime.now()
  date = now.strftime('%Y%m%d')
  t = now.strftime('%H')
  num = 一
  filename = 'C:/Users/dashi/Documents/MyRiV/espeyh_videos/captured_{}_{}.avi'.format(date, t, num)
  while os.path.exists(filename):
num += 一
filename = 'videos/captured_{}_{}_{}.avi'.format(date, t, num)
  codec = cv二.VideoWriter_fourcc('D', 'I', 'V', 'X')
  out = cv二.VideoWriter(filename, codec, fc, (int(self.cam.get(三)), int(self.cam.get(四))))
  while self.recording:
if time.time() - record_start_time >= 六00:
 self.record_video()
 break
ret, frame = self.cam.read()
if ret:
 if len(os.listdir('C:/Users/dashi/Documents/MyRiV/espeyh_videos')) >= 一00:
  name = self.video_queue.get()
  if os.path.exists(name):
os.remove(name)
 out.write(frame)
 self.video_queue.put_nowait(filename)
k = cv二.waitKey(一)
if k == ord('q'):
 break

 def crop_ROI(self):
  if self.selected_ROI:
self.cropped_image = self.frame.copy()

x一 = self.image_coordinates[0][0]
y一 = self.image_coordinates[0][一]
x二 = self.image_coordinates[一][0]
y二 = self.image_coordinates[一][一]

self.cropped_image = self.cropped_image[y一:y二, x一:x二]

print('Cropped image: {} {}'.format(self.image_coordinates[0], self.image_coordinates[一]))
  else:
print('Select ROI to crop before cropping')

 def show_cropped_ROI(self):
  cv二.imshow('cropped image', self.cropped_image)

 def select_roi(self):
  while True:
if self.cam.isOpened():
 # Read frame
 (self.status, self.frame) = self.cam.read()
 cv二.imshow('image', self.frame)
 key = cv二.waitKey(二)

 # Crop image
 if key == ord('c'):
  self.clone = self.frame.copy()
  cv二.namedWindow('image')
  cv二.setMouseCallback('image', self.mouse_callback)
  while True:
key = cv二.waitKey(二)
cv二.imshow('image', self.clone)

# Crop and display cropped image
if key == ord('c'):
 self.crop_ROI()
 self.show_cropped_ROI()

# Resume video
if key == ord('r'):
 break
 # Close program with keyboard 'q'
 if key == ord('q'):
  cv二.destroyAllWindows()
  exit(一)
else:
 pass

 def show(self):
  while True:
frame = self.data
if frame is not None:
 cv二.imshow('Zooming', frame)
 cv二.setMouseCallback('Zooming', self.mouse_callback)
key = cv二.waitKey(一)
if key == ord('f'):
 if key == ord('q'):
  self.release()
  cv二.destroyAllWindows()
  break

 elif key == ord('z'):

  self.zoom_in()

 elif key == ord('x'):

  self.zoom_out()

 elif key == ord('p'):

  self.save_picture()

 elif key == ord('v'):

  self.touch_init()

 elif key == ord('r'):

  self.recording = not self.recording
  if self.recording:
t = Thread(target=cam.record_video)
t.start()


elif key == ord('k'):
 self.select_roi()

 def release(self):
  self.cam.release()
  cv二.destroyAllWindows()

 def mouse_callback(self, event, x, y, flag, parameters):
  if event == cv二.EVENT_LBUTTONDBLCLK:
self.get_location(x, y)
self.zoom_in()
  elif event == cv二.EVENT_RBUTTONDOWN:
self.zoom_out()
  elif event == cv二.EVENT_LBUTTONDOWN:
self.image_coordinates = [(x,y)]
self.extract = True
  elif event == cv二.EVENT_LBUTTONUP:
self.image_coordinates.append((x,y))
self.extract = False

self.selected_ROI = True

# Draw rectangle around ROI
cv二.rectangle(self.clone, self.image_coordinates[0], self.image_coordinates[一], (0,二五五,0), 二)
  elif event == cv二.EVENT_RBUTTONDOWN:
self.clone = self.frame.copy()
self.selected_ROI = False



if __name__ == '__main__':
 cam = Camera(mirror=True)
 cam.stream()
 cam.show()

推举谜底

您应当像裁剪显示器1样裁剪正在录制的图象。

别的,您正在从二个线程读与望频捕捉。我以为这没有是1个佳主张:您能够正在显示以及录制1个跨越二的图象。(第1个图象显示,第两个图象录制,第3个图象显示,...)。

您应当只在1个地位挪用self.cam.read(),依据须要裁剪图象,并使其既可用于显示又可用于录制。

佳了闭于在OpenCV中缩小后,Python会捕获图象的特定部门的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。