Opencv-Python输入数组错误

时间:2017-07-09 17:04:00

标签: python arrays opencv video-capture

我最近开始探索OpenCV,我对此非常了解。我在原始视频帧内显示缩放视频帧时遇到问题。希望这是有道理的。一切正常,但当我试图改变缩放视频的颜色时,我收到一个错误。这是我的代码,希望它是自我解释的。

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while True:
    #"ret" returns a frame
    ret, frame = cap.read()

    #Draw a rectangle at given location
    cv2.rectangle(frame,(500,80),(800,380),(0,255,0),5)

    #takes a sample of the frame marked by the rectangle area(y,x)
    face_track = frame[80:380, 500:800]
    #converts the sample to gray
    grayscaled = cv2.cvtColor(face_track,cv2.COLOR_BGR2GRAY)
    #threshold range of sample
    retvl, threshold = cv2.threshold(grayscaled,125,125,cv2.THRESH_BINARY)

    #overwrites/display a new area with the sample taken by face_track in the left top corner of the frame
    frame[0:300, 0:300] = threshold

    #displays the frames captured by cap
    cv2.imshow('frame',frame)
    #cv2.imshow('frame',threshold)

    #if key stroke is 'q' break and terminate 
    if cv2.waitKey(0) & 0xff == ord('q'): 
        break

cap.release()
cv2.destroyAllWindows()

以下是错误:

  

帧[0:300,0:300] =阈值   ValueError:无法将形状(300,300)的输入数组广播为形状(300,300,3)

如果我将其更改为:

  

frame [0:300,0:300] = face_track

有效。但这不是我想要的。

另外,如果我输出阈值,那么, cv2.imshow('frame',threshold), 它也会奏效。但又不是我想要的。

cv2.cvtColor之外是否还有其他功能不会改变阵列形状。

2 个答案:

答案 0 :(得分:0)

将阈值灰色转换为BGR

cv2.cvtColor(阈值,cv2.COLOR_GRAY2BGR)

答案 1 :(得分:0)

错误在于你在三通道矩阵(8UC3)上进行单通道矩阵(8UC1)操作。

要解决此问题,您需要将单通道矩阵(灰度)转换为三通道(BGR),或者在单通道矩阵上执行单通道矩阵运算。要在python openCV中执行此操作:

cv2.cvtColor(threshold,cv2.COLOR_GRAY2BGR)