错误出现的原因应该为数据之间出了冲突,需要在某些地方调用.copy()函数。

当我查看画框后的原图和旋转后的图片时,发现它只是旋转的原图,而不是将原图直接拷贝一份再旋转。

下面为代码:

import cv2
import numpy as np

video_path=r'data.mp4'
cap = cv2.VideoCapture(video_path)

while True:
    # Run inference
    ret, img = cap.read()
    w,h,_ = img.shape
    img_ = np.rot90(img, -1)  """ 旋转函数 """

    if not ret:
        continue

    print(type(img)) """ <class 'numpy.ndarray'> """
    print(img.dtype) """ uint8 """
    print(img.shape) """ (720, 1280, 3) """
    boxes = [[-16.868, 494.49, 219.96, 657.61],
            [-39.642, 243.45, 260.06, 443.03],
            [-30.016, 442.85, 247.76, 631.59]]
    for box in boxes:
        print(1)
        """ 下面一行注释句为报错的地方 """
        # cv2.rectangle(img_, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0)) 
        cv2.rectangle(img, (int(-10), int(0)), (int(200), int(300)), (0, 255, 0))

    cv2.imshow("rot90 before", img)
    cv2.imshow("rot90 after", img_)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    exit()

 后在np.rot90(img, -1)加了“.copy()”函数后解决报错。

下面为修改后的demo:

import cv2
import numpy as np

video_path=r'data.mp4'
cap = cv2.VideoCapture(video_path)

while True:
    # Run inference

    ret, img = cap.read()
    w,h,_ = img.shape
    img_ = np.rot90(img, -1).copy()  """ 修改地方 """
    # img = cv2.getRotationMatrix2D((0, h),90,1)

    if not ret:
        continue

    print(type(img)) """ <class 'numpy.ndarray'> """
    print(img.dtype) """ uint8 """
    print(img.shape) """ (720, 1280, 3) """
    boxes = [[-16.868, 494.49, 219.96, 657.61],
            [-39.642, 243.45, 260.06, 443.03],
            [-30.016, 442.85, 247.76, 631.59]]
    for box in boxes:
        print(1)
        cv2.rectangle(img_, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0))
        cv2.rectangle(img, (int(-10), int(0)), (int(200), int(300)), (0, 255, 0))

    cv2.imshow("rot90 before", img)
    cv2.imshow("rot90 after", img_)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    exit()

作者:阳一子

本文地址:https://blog.csdn.net/qq_279033270/article/details/109750634

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐