【问题标题】:Why aren't my sets containing more than one element?- python 2.7为什么我的集合不包含一个以上的元素?- python 2.7
【发布时间】:2023-03-10 22:08:01
【问题描述】:

好的,所以我写了一些代码,我想比较两组。但是,长度只会返回 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?

谢谢

【问题讨论】:

  • 这很难理解。请发MCVE

标签: python list set elements


【解决方案1】:

您的代码中有一些错误。看起来您正在将所有颜色读入一个字符串。如果您想要一组颜色,则需要拆分字符串:

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 三元组编码为单个字符串,那么您 必须 将所有值填充为零:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2012-12-01
    • 2012-05-25
    相关资源
    最近更新 更多