so in my current code I'm using
im_set=set(map(tuple, im_list[0]))
to convert a list into a set. However it's very slow. Is there a faster/ none map method to speed things up? This is my current code
while True:
cam = cv2.VideoCapture(0)
start=time.time()
while(cam.isOpened()): #Opens camera
ret, im = cam.read() #Takes screenshot
#im=cv2.imread('RGB.png')
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()
im_set=set(map(tuple, im_list[0]))
ColourCount= set(im_set) & set(om_set)
print len(ColourCount)
print N
end=time.time()-start
print end
Note that om_set is from a different program.
Anyway, basically I have to convert an np.array to a set, and compare that set to see what overlaps with them. But, its very slow. Is there a method I can use to speed up this conversion?
If you were using Python 3, that would be fast; but in Python 2, you should use a set comprehension:
im_set = {tuple(item) for item in im_list[0]}
map()
is slower in Python 2 because it returns a list. That means that each tuple is stored in memory before you even start creating a set. This way, however, you are adding each item to the set as it is converted to a tuple.
Using itertools.imap is going to be faster:
In [18]: from itertools import imap
In [19]: timeit set(imap(tuple, l))
100 loops, best of 3: 2.27 ms per loop
In [20]: timeit {tuple(item) for item in l}
100 loops, best of 3: 2.69 ms per loop
You also don't need to create extra sets, you use the ones you have created and use set.intersection :
im_set.intersection(om_set)
Unless you specifically need lists this can also all be done using numpy .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.