gpt4 book ai didi

python - 删除视频帧的边框/边距

转载 作者:行者123 更新时间:2023-12-02 16:14:50 26 4
gpt4 key购买 nike

我正在处理带有边框(边距)的视频。有些在所有四个侧面上都有,有些只在左右两侧,有些只在顶部和底部。这些边距的长度也不固定。
我正在从这些视频中提取帧,例如,

enter image description here



enter image description here

这两个都在顶部和底部包含边框。

任何人都可以建议一些方法从这些图像中删除这些边界(最好是在Python中)。
我遇到了一些方法,例如Stackoverflow上的this,但这可以处理边界完全为黑色(0,0,0)的理想情况。但就我而言,它们可能不是黑色的,也可能包含抖动的声音。
任何帮助/建议将不胜感激。

最佳答案

这是在Python / OpenCV中执行此操作的一种方法。

  • 阅读图片
  • 转换为灰度并反转
  • 阈值
  • 应用形态学去除小的黑色或白色区域,然后再次反转
  • 获取一个区域的轮廓
  • 获取该轮廓的边框
  • 使用numpy slice 来裁剪图像的该区域以形成结果图像
  • 保存生成的图像

  • import cv2
    import numpy as np

    # read image
    img = cv2.imread('gymnast.png')

    # convert to grayscale
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    # invert gray image
    gray = 255 - gray

    # gaussian blur
    blur = cv2.GaussianBlur(gray, (3,3), 0)

    # threshold
    thresh = cv2.threshold(blur,236,255,cv2.THRESH_BINARY)[1]

    # apply close and open morphology to fill tiny black and white holes
    kernel = np.ones((5,5), np.uint8)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

    # invert thresh
    thresh = 255 -thresh

    # get contours (presumably just one around the nonzero pixels)
    # then crop it to bounding rectangle
    contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = contours[0] if len(contours) == 2 else contours[1]
    cntr = contours[0]
    x,y,w,h = cv2.boundingRect(cntr)
    crop = img[y:y+h, x:x+w]

    cv2.imshow("IMAGE", img)
    cv2.imshow("THRESH", thresh)
    cv2.imshow("CROP", crop)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # save cropped image
    cv2.imwrite('gymnast_crop.png',crop)
    cv2.imwrite('gymnast_crop.png',crop)

    输入:

    enter image description here

    阈值和清理后的图像:

    enter image description here

    裁剪结果:

    enter image description here

    关于python - 删除视频帧的边框/边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60571974/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com