【问题标题】:How to resize frame's from video with aspect ratio如何从具有宽高比的视频中调整帧的大小
【发布时间】:2017-09-05 00:51:28
【问题描述】:

我正在使用 Python 2.7,OpenCV。我已经写了这段代码。

import cv2
vidcap = cv2.VideoCapture('myvid2.mp4')
success,image = vidcap.read()
count = 0;
print "I am in success"
while success:
  success,image = vidcap.read()
  resize = cv2.resize(image, (640, 480)) 
  cv2.imwrite("%03d.jpg" % count, resize)     
  if cv2.waitKey(10) == 27:                     
      break
  count += 1

我正在处理视频并将视频分成单独的帧,作为 .jpg 图像。同时,我还将框架的大小调整为 640x480。帧的顺序也被保留。代码的唯一问题是它没有保存以前的图像比例。

例如,从 1920x1080 调整大小:

如您所见,比率存在问题。 1920x1080 16:9,但 640:480 4:3

我理想中的样子:

感谢您抽出宝贵时间阅读问题。如果你能帮我解决这个问题,我会很高兴的~ 祝你有美好的一天,我的朋友。

【问题讨论】:

    标签: python image opencv video resize


    【解决方案1】:

    您可以将原始帧的高度和宽度除以一个值并将其作为参数提供,而不是使用硬编码值 640 和 480,如下所示:

    import cv2
    
    vidcap = cv2.VideoCapture("/path/to/video")
    success, image = vidcap.read()
    count = 0
    
    while success:
        height, width, layers = image.shape
        new_h = height / 2
        new_w = width / 2
        resize = cv2.resize(image, (new_w, new_h))
        cv2.imwrite("%03d.jpg" % count, resize)
        success, image = vidcap.read()
        count += 1
    

    【讨论】:

      【解决方案2】:

      请试试这个。它应该会给你预期的输出。

       def resize_image(image, width, height,COLOUR=[0,0,0]):
          h, w, layers = image.shape
          if h > height:
              ratio = height/h
              image = cv2.resize(image,(int(image.shape[1]*ratio),int(image.shape[0]*ratio)))
          h, w, layers = image.shape
          if w > width:
              ratio = width/w
              image = cv2.resize(image,(int(image.shape[1]*ratio),int(image.shape[0]*ratio)))
          h, w, layers = image.shape
          if h < height and w < width:
              hless = height/h
              wless = width/w
              if(hless < wless):
                  image = cv2.resize(image, (int(image.shape[1] * hless), int(image.shape[0] * hless)))
              else:
                  image = cv2.resize(image, (int(image.shape[1] * wless), int(image.shape[0] * wless)))
          h, w, layers = image.shape
          if h < height:
              df = height - h
              df /= 2
              image = cv2.copyMakeBorder(image, int(df), int(df), 0, 0, cv2.BORDER_CONSTANT, value=COLOUR)
          if w < width:
              df = width - w
              df /= 2
              image = cv2.copyMakeBorder(image, 0, 0, int(df), int(df), cv2.BORDER_CONSTANT, value=COLOUR)
          image = cv2.resize(image,(1280,720),interpolation=cv2.INTER_AREA)
          return image
      

      【讨论】:

        【解决方案3】:

        想补充一下萨兰什提到的关于划分的内容。除法效果很好,但我相信resize 函数期望新维度是int 对象,因此请确保使用int(x)round(x, 0) 函数这样做。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-07
          • 2015-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多