为什么我的集合不包含多个元素? - python 2.7

时间:2016-05-09 15:13:50

标签: python list set elements

好的,所以我写了一些代码,我想比较两组。但是,长度将仅返回0或1,具体取决于我使用的是两张图像还是相同的图像。这是因为我的集合仅形成1个元素集而不是将数字分开。例如,这些集合读作[(a,b,c)]而不是[('a','b','c')]。

这是我的代码

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 个答案:

答案 0 :(得分: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,38,78)?您需要更改这些颜色字符串写入文件的方式,因为您的格式不明确。为了简单起见,为什么不把它写成这样的文件:

13 10 78
255 255 0

如果您坚持将rgb三元组编码为单个字符串,那么您将零填充所有值:

## 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

如果要在图像中创建所有不同颜色的并集。

如果您在解决这些问题后仍有问题,我建议您使用更新后的代码发布新问题。