Python 3.x openCV2错误

Python 3.x openCV2错误,python-3.x,opencv,chromakey,Python 3.x,Opencv,Chromakey,我是新的编码。使用此脚本: from PIL import Image from PIL.ImageChops import subtract import numpy, math, time, glob, sys, os, logging, requests, random def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None,tolerance=None): """ http://gc-films

我是新的编码。使用此脚本:

from PIL import Image
from PIL.ImageChops import subtract
import numpy, math, time, glob, sys, os, logging, requests, random

def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None,tolerance=None):
    """
    http://gc-films.com/chromakey.html
    http://www.cs.utah.edu/~michael/chroma/
    :param infile:      Greenscreen image location
    :param inbg:        Background image location
    :param outfile:     Output file location
    :param keyColor:    greenscreen color; it can be any singular color
    :param tolerance:   tolerance of cleaning
    :return:
    """

    if not keyColor:
        keyColor = [151,44,21] #Y,Cb, and Cr values of the greenscreen

    if not tolerance:
        tolerance = [100,130] #Allowed Distance from Values

    #open files
    inDataFG = Image.open('/home/leonardo/Scrivania/in/KVfnt.png').convert('YCbCr')
    Path = '/home/leonardo/Scrivania/background/'
    FullPath = os.path.join(Path, random.choice(os.listdir(Path)))
    BG = Image.open(FullPath).convert('RGB')
    [Y_key, Cb_key, Cr_key] = keyColor
    [tola, tolb]= tolerance

    (x,y) = inDataFG.size #get dimensions
    foreground = numpy.array(inDataFG.getdata()) #make array from image
    maskgen = numpy.vectorize(colorclose) #vectorize masking function


    alphaMask = maskgen(foreground[:,1],foreground[:,2] ,Cb_key, Cr_key, tola, tolb) #generate mask
    alphaMask.shape = (y,x) #make mask dimensions of original image
    imMask = Image.fromarray(numpy.uint8(alphaMask))#convert array to image
    invertMask = Image.fromarray(numpy.uint8(255-255*(alphaMask/255))) #create inverted mask with extremes

    #create images for color mask
    colorMask = Image.new('RGB',(x,y),tuple([0,0,0]))
    allgreen = Image.new('YCbCr',(x,y),tuple(keyColor))

    colorMask.paste(allgreen,invertMask) #make color mask green in green values on image
    inDataFG = inDataFG.convert('RGB') #convert input image to RGB for ease of working with
    cleaned = subtract(inDataFG,colorMask) #subtract greens from input
    BG.paste(cleaned,imMask)#paste masked foreground over background

    # BG.show() #display cleaned image
    BG.save(outfile, "JPEG") #save cleaned image

def colorclose(Cb_p,Cr_p, Cb_key, Cr_key, tola, tolb):
    temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2)
    if temp < tola:
        z = 0.0
    elif temp < tolb:
        z = ((temp-tola)/(tolb-tola))
    else:
        z = 1.0
    return 255.0*z

def check_folders(logger):
    if not os.path.exists('out/'):
        os.mkdir('out/')
    if not os.path.exists('background/'):
        os.mkdir('background/')
        logger.error("Place background images in background/")
        sys.exit()
    if not os.path.exists('in/'):
        os.mkdir('in/')
        logger.error("Place input files in in/")
        sys.exit()

def begin_greenbox(logger):
    """
    For all backgrounds loop through all input files into the out file
    """
    for bg in glob.glob('background/*'):
            continue
    bg_name = bg.split('/')[-1].lower().strip('.jpg').strip('.png').strip('.jpeg')
    for picture in glob.glob('in/*'):
                continue
    pic_name = picture.split('/')[-1].lower().strip('.JPG').strip('.png').strip('.jpeg')
    output_file = 'out/' + bg_name + ' ' + pic_name + '.jpg'

    one_pic = time.time()
    GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
    one_pic_time_done = time.time()

    time_arr.append(one_pic_time_done-one_pic)
    logger.info(time_arr)
    logger.info('done : %s' % pic_name)

def start_logging():
    logging.basicConfig()
    logger = logging.getLogger('greenbox')
    logger.setLevel(logging.INFO)
    return logger

if __name__ == '__main__':
    time_start = time.time()
    time_arr = []
    logger = start_logging()
    logger.info("Start time: %s" % time_start)
    check_folders(logger)    
    begin_greenbox(logger)
    time_end = time.time()
    logger.info("End time: %s" % time_end)
一切正常,图像从相机捕获并保存在文件夹中。如果将第二个代码添加到第一个代码:

from PIL import Image
from PIL.ImageChops import subtract
import numpy, math, time, glob, sys, os, logging, requests, random
from cv2 import *

# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",WINDOW_AUTOSIZE)
    imwrite('/home/leonardo/Scrivania/in/KVfnt.png',img) #save image 
def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None,tolerance=None):
    """
    http://gc-films.com/chromakey.html
    http://www.cs.utah.edu/~michael/chroma/
    :param infile:      Greenscreen image location
    :param inbg:        Background image location
    :param outfile:     Output file location
    :param keyColor:    greenscreen color; it can be any singular color
    :param tolerance:   tolerance of cleaning
    :return:
    """

    if not keyColor:
        keyColor = [151,44,21] #Y,Cb, and Cr values of the greenscreen

    if not tolerance:
        tolerance = [100,130] #Allowed Distance from Values

    #open files
    inDataFG = Image.open('/home/leonardo/Scrivania/in/KVfnt.png').convert('YCbCr')
    Path = '/home/leonardo/Scrivania/background/'
    FullPath = os.path.join(Path, random.choice(os.listdir(Path)))
    BG = Image.open(FullPath).convert('RGB')
    [Y_key, Cb_key, Cr_key] = keyColor
    [tola, tolb]= tolerance

    (x,y) = inDataFG.size #get dimensions
    foreground = numpy.array(inDataFG.getdata()) #make array from image
    maskgen = numpy.vectorize(colorclose) #vectorize masking function


    alphaMask = maskgen(foreground[:,1],foreground[:,2] ,Cb_key, Cr_key, tola, tolb) #generate mask
    alphaMask.shape = (y,x) #make mask dimensions of original image
    imMask = Image.fromarray(numpy.uint8(alphaMask))#convert array to image
    invertMask = Image.fromarray(numpy.uint8(255-255*(alphaMask/255))) #create inverted mask with extremes

    #create images for color mask
    colorMask = Image.new('RGB',(x,y),tuple([0,0,0]))
    allgreen = Image.new('YCbCr',(x,y),tuple(keyColor))

    colorMask.paste(allgreen,invertMask) #make color mask green in green values on image
    inDataFG = inDataFG.convert('RGB') #convert input image to RGB for ease of working with
    cleaned = subtract(inDataFG,colorMask) #subtract greens from input
    BG.paste(cleaned,imMask)#paste masked foreground over background

    # BG.show() #display cleaned image
    BG.save(outfile, "JPEG") #save cleaned image

def colorclose(Cb_p,Cr_p, Cb_key, Cr_key, tola, tolb):
    temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2)
    if temp < tola:
        z = 0.0
    elif temp < tolb:
        z = ((temp-tola)/(tolb-tola))
    else:
        z = 1.0
    return 255.0*z

def check_folders(logger):
    if not os.path.exists('out/'):
        os.mkdir('out/')
    if not os.path.exists('background/'):
        os.mkdir('background/')
        logger.error("Place background images in background/")
        sys.exit()
    if not os.path.exists('in/'):
        os.mkdir('in/')
        logger.error("Place input files in in/")
        sys.exit()

def begin_greenbox(logger):
    """
    For all backgrounds loop through all input files into the out file
    """
    for bg in glob.glob('background/*'):
            continue
    bg_name = bg.split('/')[-1].lower().strip('.jpg').strip('.png').strip('.jpeg')
    for picture in glob.glob('in/*'):
                continue
    pic_name = picture.split('/')[-1].lower().strip('.JPG').strip('.png').strip('.jpeg')
    output_file = 'out/' + bg_name + ' ' + pic_name + '.jpg'

    one_pic = time.time()
    GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
    one_pic_time_done = time.time()

    time_arr.append(one_pic_time_done-one_pic)
    logger.info(time_arr)
    logger.info('done : %s' % pic_name)

def start_logging():
    logging.basicConfig()
    logger = logging.getLogger('greenbox')
    logger.setLevel(logging.INFO)
    return logger

if __name__ == '__main__':
    time_start = time.time()
    time_arr = []
    logger = start_logging()
    logger.info("Start time: %s" % time_start)
    check_folders(logger)    
    begin_greenbox(logger)
    time_end = time.time()
    logger.info("End time: %s" % time_end)
从PIL导入图像
从PIL.ImageChops导入减法
导入numpy、数学、时间、全局、系统、操作系统、日志、请求、随机
从cv2进口*
#初始化相机
cam=视频捕获(0)#0->摄像机索引
s、 img=cam.read()
如果s:#捕获的帧没有任何错误
namedWindow(“cam测试”,窗口自动调整)
imwrite('/home/leonardo/Scrivania/in/KVfnt.png',img)#保存图像
def绿色屏幕(infle、inbg、outfile='output.png',keyColor=None,tolerance=None):
"""
http://gc-films.com/chromakey.html
http://www.cs.utah.edu/~z~迈克尔/色度/
:param infle:绿色屏幕图像位置
:param inbg:背景图像位置
:param outfile:输出文件位置
:param keyColor:绿色屏幕颜色;可以是任何单色
:参数公差:清洁公差
:返回:
"""
如果不是keyColor:
keyColor=[151,44,21]#绿色屏幕的Y、Cb和Cr值
如果不是公差:
公差=[100130]#与数值的允许距离
#打开文件
inDataFG=Image.open('/home/leonardo/Scrivania/in/KVfnt.png')。convert('YCbCr'))
路径='/home/leonardo/Scrivania/background/'
FullPath=os.path.join(path,random.choice(os.listdir(path)))
BG=Image.open(FullPath.convert('RGB'))
[Y_键、Cb_键、Cr_键]=keyColor
[tola,tolb]=公差
(x,y)=inDataFG.size#获取尺寸
前台=numpy.array(inDataFG.getdata())#从图像生成数组
maskgen=numpy.vectorize(colorclose)#矢量化掩蔽函数
alphaMask=maskgen(前景[:,1],前景[:,2],Cb_键,Cr_键,tola,tolb)#生成掩码
alphaMask.shape=(y,x)#制作原始图像的遮罩尺寸
imMask=Image.fromarray(numpy.uint8(alphaMask))#将数组转换为图像
InverseMask=Image.fromarray(numpy.uint8(255-255*(alphaMask/255))#创建具有极端值的反转掩码
#为颜色遮罩创建图像
colorMask=Image.new('RGB',(x,y),元组([0,0,0]))
allgreen=Image.new('YCbCr',(x,y),元组(keyColor))
彩色蒙版。粘贴(全绿,反转蒙版)#使彩色蒙版在图像上的绿色值为绿色
inDataFG=inDataFG.convert('RGB')#将输入图像转换为RGB以便于使用
清洁=减去(inDataFG,彩色蒙版)#从输入中减去绿色
背景粘贴(已清洁,imMask)#将遮罩前景粘贴到背景上
#BG.show()#显示已清理的图像
BG.save(outfile,“JPEG”)#保存清理过的图像
def彩色关闭(Cb_p、Cr_p、Cb_键、Cr键、tola、tolb):
温度=数学sqrt((Cb_键-Cb_p)**2+(Cr_键-Cr_p)**2)
如果温度
我得到这个错误:

  File "chromakey+upload.py", line 116, in <module>
    begin_greenbox(logger)
  File "chromakey+upload.py", line 97, in begin_greenbox
    GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
  File "chromakey+upload.py", line 56, in GreenScreen
    cleaned = subtract(inDataFG,colorMask) #subtract greens from input
TypeError: src1 is not a numpy array, neither a scalar
文件“chromakey+upload.py”,第116行,在
开始绿盒(记录器)
文件“chromakey+upload.py”,第97行,在begin\u绿框中
绿色屏幕(infle=picture,inbg=bg,outfile=output\u文件)
文件“chromakey+upload.py”,第56行,绿色屏幕
清洁=减去(inDataFG,彩色蒙版)#从输入中减去绿色
TypeError:src1不是numpy数组,也不是标量
有什么问题?感谢您的回答。

正如错误所说:

src1不是numpy数组,也不是标量数组

也许,你应该试试:

cleaned = subtract(numpy.array(inDataFG.getdata()),numpy.array(colorMask.getdata()))
编辑
减法上存在“冲突”:

from PIL.ImageChops import subtract # first subtract
from cv2 import * # OpenCV has a subtract too
这是在调用中使用名称空间的原因之一


如果你的主图像库是PIL,也许你应该在需要时导入cv2并使用cv2.

但是如果我从文件夹中获取图像,一切正常,如果我从网络摄像头获取图像,我会出现此错误。
冲突减去
,请阅读我的编辑。您认为您使用的是从PIL.Image中减去
subtract
,而调用的是
cv2.substract
,您应用了相同的
PIL.Image->numpy.array
转换到
colorMask
?好的,我已经在从网络摄像头获取图像的脚本之后移动了“from PIL.imageschops import subtract”,现在一切都好了。非常感谢你!!
from PIL.ImageChops import subtract # first subtract
from cv2 import * # OpenCV has a subtract too