2016-05-09 40 views
0

好的,所以我写了一些代码,我想比较两个集合。但是,长度将只返回0或1,具体取决于我使用的是两张图像还是同一张图像。这是因为我的套装只有1套,而不是将数字混合在一起。例如,这些集合读为[(a,b,c)]而不是[('a','b','c')]。为什么我的集合不包含多个元素? - python 2.7

这里是我的代码

import cv2 
import numpy as np 
import time 
N=0 
colour=[] 
colourfile=open('Green from RGB.txt', 'r') 
for line in colourfile.readlines(): 
    colour.append([line]) 
colour_set=sorted(set(map(tuple, colour))) 



def OneNumber(im): #Converts the pixels rgb to a single number. 
    temp_im=im.astype('int32') 
    r,g,b = temp_im[:,:,0], temp_im[:,:,1], temp_im[:,:,2] 
    combo=r*1000000+g*1000+b 
    return combo 



while True: 
    cam = cv2.VideoCapture(0) 
    start=time.time() 
    while(cam.isOpened()):     #Opens camera 
     ret, im = cam.read()    #Takes screenshot 
     #im=cv2.imread('filename.type') 
     im=cv2.resize(im,(325,240))   #Resize to make it faster 
     im= im.reshape(1,-1,3) 
     im=OneNumber(im)    #Converts the pixels rgb to a singe number 
     im_list=im.tolist()     #Makes it into a list 
     im_set=set(im_list[0])    #Makes set 
     ColourCount= set(colour_set) & set(colour_set) #or set(im_set) for using/ comparing camera 
     print len(ColourCount) 

而且文本文件我开写为:

126255104, 8192000, 249255254, 131078, 84181000, 213254156, 

在一个单一的,伟大的大线。

所以基本上,我如何将数字分成集合中的不同元素im_set和colour_set?

谢谢

+1

这很难遵循。请制作[MCVE](http://stackoverflow.com/help/mcve)。 – timgeb

回答

0

您的代码中有一些错误。它看起来像你正在阅读所有的颜色成一个单一的字符串。你需要,而不是如果你想要一组颜色来分割字符串:

for line in colourfile.readlines(): 
    temp_line = [x.strip() for x in line.split(',')] ## create a temporary list, splitting on commas, and removing extra whitesapce 
    colour.extend(temp_line) ## don't put brackets around `line`, you add another "layer" of lists to the list 
    ## also don't `append` a list with a list, use `extend()` instead 
#colour_set=sorted(set(map(tuple, colour))) ## I think you're trying to convert a string to a 3-tuple of rgb color values. This is not how to do that 

你必须与你的RGB颜色表示一个严重的问题:什么是131078?是(13,10,78)还是(131,0,78)或(1,31,78)?您需要更改将这些颜色字符串写入文件的方式,因为您的格式不明确。为了保持它的简单,为什么不把它写入这样一个文件:

13 10 78 
255 255 0 

如果你坚持编码RGB三元作为一个字符串,那么你HAVE零垫的所有值:

## for example 
my_rgb = (13,10,78) 
my_rgb_string = "%03d%03d%03d" % (r, g, b) ## zero-pad to exactly 3 digit width 
print(my_rgb_string) 
>> 013010078 

另一个问题是:你是相交的一组与自身,而不是交叉的两组不同:

ColourCount= set(colour_set) & set(colour_set) #or set(im_set) for using/ comparing camera 

应该是这样的:

ColourCount= set(colour_set) | im_set #or set(im_set) for using/ comparing camera 

如果您想创建图像中所有不同颜色的联合。

如果解决这些问题后仍然有问题,我建议您发布一个新的问题与更新的代码。

相关问题