kandi background
kandi background
Explore Kits
kandi background
Explore Kits
Computer vision is a field of artificial intelligence and computer science that aims at giving the computers visual understanding capabilities. When we humans see something, we can easily interpret what we see and understand its meaning based on our past experience. For example if you see a picture of a dog, you’ll immediately know that it’s a dog. But if you show the same picture to an untrained computer, it won’t be able to interpret the contents of this image and tell you that it’s a dog. The main goal of computer vision is to make the computers see in the same way as humans do so they can understand images in more complex ways than just identifying objects by their shape.

Computer vision tasks include methods for acquiring, processing, analyzing and understanding digital images, and extraction of high-dimensional data from the real world in order to produce numerical or symbolic information, e.g., in the forms of decisions. Understanding in this context means the transformation of visual images (the input of the retina) into descriptions of the world that can interface with other thought processes and elicit appropriate action

Popular New Releases in Computer Vision

OpenCV 4.5.5

5.1.0

Tesseract.js v2.1.5

OpenPose v1.7.0

opencv

OpenCV 4.5.5

tesseract

5.1.0

tesseract.js

Tesseract.js v2.1.5

openpose

OpenPose v1.7.0

sharp

Popular Libraries in Computer Vision

Trending New libraries in Computer Vision

Top Authors in Computer Vision

1

35 Libraries

8442

2

33 Libraries

80538

3

24 Libraries

1988

4

24 Libraries

711

5

20 Libraries

54

6

16 Libraries

34

7

16 Libraries

61

8

16 Libraries

4424

9

15 Libraries

1568

10

15 Libraries

605

1

35 Libraries

8442

2

33 Libraries

80538

3

24 Libraries

1988

4

24 Libraries

711

5

20 Libraries

54

6

16 Libraries

34

7

16 Libraries

61

8

16 Libraries

4424

9

15 Libraries

1568

10

15 Libraries

605

Trending Kits in Computer Vision

hand-emoji-detector

Build AI Powered Emoji Detector

<img src="https://kandi.dev/owassets/ai-powered-emoji-detector-banner.png" alt="Emoji Detector" style="height:auto;max-width:100%;"/> AI powered emoji detector can be used by the companies to increase engagement with their customers. They can create personalized content for their users, which will help them in building a strong relationship with their customers. The emoji detector will help you in analyzing your audience and their preferences so that you can deliver the right content. You can also use the technology to provide customer support to your customers by providing customized answers. One of the most important aspects of AI Powered Emoji Detector is that it will help you in detecting any kind of emotions and expressions on your face OR hand gestures from web camera. It will help in detecting whether you are happy, sad or angry and so on. This technology is also used for predicting different kinds of expressions like happiness, fear, sadness etc. kandi kit provides you with a fully deployable Use of AI Powered Emoji Detector. Source code included so that you can customize it for your requirement. <button class="MuiButtonBase-root MuiButton-root MuiButton-contained editexp MuiButton-containedSecondary click_collections_oneclickfiledownload " onclick="location.href='https://github.com/kandikits/Emojinator/raw/master/kit_installer.zip'" type="button"> ⬇️ Download 1-Click Installer </button>

kandi

1-Click Install

csharp-computer-vision

13 best C# Computer Vision

Computer vision is a discipline within computer science that focuses on how computers can gain an understanding of the visual world. Typically, this involves capturing image data from a camera and using specialized algorithms to extract information about objects, locations, and people involved in an image. This can range from detecting whether a face is smiling or frowning to identifying what kind of car is parked in front of a building. Computer vision has applications in many fields including medicine, entertainment, law enforcement, and more—and C# is one of the most popular programming languages used for computer vision. Some of the most popular among developers are: Opencvsharp - Provides functions for converting from Mat into Bitmap(GDI+) or WriteableBitmap(WPF); OptiKey - An on-screen keyboard that is designed to help Motor Neuron Disease (MND) patients interact with Windows computers; OpenCV - ComputerVision Demos. The entire list of open source C# Computer Vision libraries are provided below.

python-computer-vision

19 best Python Computer Vision

Python programming language employs NumPy arrays in order to achieve image processing and computer vision tasks in the applications of artificial intelligence. The gamut of computer vision tasks can be executed efficiently with Python's scikit image processing libraries that work in tandem with NumPy arrays to produce high-quality filtered images. In fact, a Python imaging library can be used to accomplish complex tasks such as feature extraction, face recognition, and image manipulation. In addition, the scikit learn library in Python provides deep learning modules to employ in business operations (for example, for consumer satisfaction analysis). <br/> <br/> Check out these libraries for Python computer vision to create a state-of-the-art code to deploy in data science fields. The face_recognition library touts to be the simplest API in the world for Python and command-line. If you are aiming to achieve image-to-image translation, check out the pytorch-CycleGAN-and-pix2pix library. One of the highest utility libraries in the list is perhaps the EasyOCR - a code pack for optical character recognition in over 80 languages. If machine learning is your objective, the NumPy_ML library carries pre-coded modules to insert into your code.

python-object-detection

Object Detection

<img src="https://kandi.dev/owassets/python-object-detection-libraries-banner.png" alt="Python Object Detection Libraries" style="height:auto;max-width:100%;"/> Python object detection libraries are used for detecting an object in an image. It is a computer vision library that can detect the objects present in images and videos. The Python object detection libraries can be used to build a machine learning model for detecting objects in the images or videos. One of the best in class, Detectron, is Facebook AI Research’s software system that performs object detection with various state-of-the-art machine learning algorithms like Mask R-CNN. It is powered by the Caffe2 deep learning framework with the goal to provide a high-quality codebase for object detection research. Pillow or PIL is another open-source Python library for image processing. With it, you can read, rescale, and save images in different formats. Part of the OpenMMLab project, MMDetection is a PyTorch-based object detection toolbox. The following is a comprehensive list of the best open-source libraries that you can use for object detection:

akshara-kit

Computer Vision : Series

𝐂𝐎𝐌𝐏𝐔𝐓𝐄𝐑 𝐕𝐈𝐒𝐈𝐎𝐍 is a field of artificial intelligence that trains computers to interpret and understand the visual world. Using digital images from cameras and videos and deep learning models machines can accurately identify and classify objects and then react to what they "see". It is the field of computer science that focuses on replicating parts of the complexity of the <b>human vision</b> system and enabling computers to identify and process objects in images and videos. <center><img src="http://drive.google.com/uc?export=view&id=13ESwkbCxMOOlNsiBTpsp-xsmXwKd48pF" width="530" height="300" ></center> <u>𝑯𝑰𝑺𝑻𝑶𝑹𝒀 𝑶𝑭 𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵:</u> <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > In the <b>1950s</b>, using some of the first neural networks to detect the edges of an object and to sort simple objects into categories like circles. <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > In the <b>1970s</b>, the first commercial use of computer vision interpreted typed or handwritten text using optical character recognition. <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > In the <b>1990s</b>, making large sets of images available online for analysis, facial recognition programs flourished. <u>𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵 𝑾𝑶𝑹𝑲𝑰𝑵𝑮:</u> <img src="http://drive.google.com/uc?export=view&id=1PNC5BwrEB9Xw3y3exIm7YQuOKe-BapA8" width="50" height="32" align = "left" HSPACE="20" / >Acquiring an image <img src="http://drive.google.com/uc?export=view&id=1I1t9YJbGBETFXgek5fBETJOzMsrW7cr4" width="50" height="32" align = "left" HSPACE="20" / >Processing the image <img src="http://drive.google.com/uc?export=view&id=1S4St91tYg8oF7fyUUMoeLEJhj4BiBJLb" width="50" height="32" align = "left" HSPACE="20" / >Understanding the image <u>𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵 𝑨𝑺 𝑨 𝑱𝑰𝑮𝑺𝑨𝑾 𝑷𝑼𝒁𝒁𝑳𝑬:</u> Computers assemble visual images like a jigsaw puzzle. All these pieces of the jigsaw are to be assembled into an image and that's how neural networks work for computer vision. They distinguish many different pieces of the image, they identify the edges and then model the subcomponents. Using filtering and a series of actions through deep network layers, they can piece all the parts of the image together. the computer is often fed hundreds or thousands of related images for training and recognizing specific objects. <u>𝑨𝑷𝑷𝑳𝑰𝑪𝑨𝑻𝑰𝑶𝑵 𝑶𝑭 𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵:</u> <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > Computer Vision for Defect Detection <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5"/ > Computer Vision for Intruder Detection <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5"/ > Computer Vision for Screen Reader <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > Computer Vision for Code and Character Reader (OCR) <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5"/ > Computer Vision in robotics for Bin Picking <style> div { text-align: justify; text-justify: inter-word; } </style>

computer-vision-concepts

Face Recognition and OpenCV

What is face recognition and how does it work? First of all what is recognition? Let's take an example, the first thing that comes to mind when you see an orange fruit is that it is an orange fruit. In simple terms, your mind telling you that this is an orange fruit, is recognition. So, what exactly is face recognition? I'm confident you guessed correctly. You identify your friend Bob when you see him strolling down the street or when you see a photo of him. But, more importantly, how does face recognition work? It's easy to use and understand. Consider this scenario: you meet someone for the first time in your life and you don't recognize him, right? You examine his face, eyes, nose, lips, color, and overall appearance while he speaks or shakes your hand. This is your mind learning or training to recognize that person's face by collecting face data.  The next question is how to implement face recognition using OpenCV and other open source libraries? So, there you have it. You would argue that human minds can easily do these things, but programming them into a machine is tough. Don't worry, it's not the case. Face recognition is as simple as it appears thanks to different open source libraries . Face recognition follows the same coding techniques as the real-life example we examined earlier.

hand-emoji-detector

Build AI Powered Emoji Detector

<img src="https://kandi.dev/owassets/ai-powered-emoji-detector-banner.png" alt="Emoji Detector" style="height:auto;max-width:100%;"/> AI powered emoji detector can be used by the companies to increase engagement with their customers. They can create personalized content for their users, which will help them in building a strong relationship with their customers. The emoji detector will help you in analyzing your audience and their preferences so that you can deliver the right content. You can also use the technology to provide customer support to your customers by providing customized answers. One of the most important aspects of AI Powered Emoji Detector is that it will help you in detecting any kind of emotions and expressions on your face OR hand gestures from web camera. It will help in detecting whether you are happy, sad or angry and so on. This technology is also used for predicting different kinds of expressions like happiness, fear, sadness etc. kandi kit provides you with a fully deployable Use of AI Powered Emoji Detector. Source code included so that you can customize it for your requirement. <button class="MuiButtonBase-root MuiButton-root MuiButton-contained editexp MuiButton-containedSecondary click_collections_oneclickfiledownload " onclick="location.href='https://github.com/kandikits/Emojinator/raw/master/kit_installer.zip'" type="button"> ⬇️ Download 1-Click Installer </button>

kandi

1-Click Install

akshara-kit

Computer Vision : Series

𝐂𝐎𝐌𝐏𝐔𝐓𝐄𝐑 𝐕𝐈𝐒𝐈𝐎𝐍 is a field of artificial intelligence that trains computers to interpret and understand the visual world. Using digital images from cameras and videos and deep learning models machines can accurately identify and classify objects and then react to what they "see". It is the field of computer science that focuses on replicating parts of the complexity of the <b>human vision</b> system and enabling computers to identify and process objects in images and videos. <center><img src="http://drive.google.com/uc?export=view&id=13ESwkbCxMOOlNsiBTpsp-xsmXwKd48pF" width="530" height="300" ></center> <u>𝑯𝑰𝑺𝑻𝑶𝑹𝒀 𝑶𝑭 𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵:</u> <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > In the <b>1950s</b>, using some of the first neural networks to detect the edges of an object and to sort simple objects into categories like circles. <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > In the <b>1970s</b>, the first commercial use of computer vision interpreted typed or handwritten text using optical character recognition. <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > In the <b>1990s</b>, making large sets of images available online for analysis, facial recognition programs flourished. <u>𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵 𝑾𝑶𝑹𝑲𝑰𝑵𝑮:</u> <img src="http://drive.google.com/uc?export=view&id=1PNC5BwrEB9Xw3y3exIm7YQuOKe-BapA8" width="50" height="32" align = "left" HSPACE="20" / >Acquiring an image <img src="http://drive.google.com/uc?export=view&id=1I1t9YJbGBETFXgek5fBETJOzMsrW7cr4" width="50" height="32" align = "left" HSPACE="20" / >Processing the image <img src="http://drive.google.com/uc?export=view&id=1S4St91tYg8oF7fyUUMoeLEJhj4BiBJLb" width="50" height="32" align = "left" HSPACE="20" / >Understanding the image <u>𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵 𝑨𝑺 𝑨 𝑱𝑰𝑮𝑺𝑨𝑾 𝑷𝑼𝒁𝒁𝑳𝑬:</u> Computers assemble visual images like a jigsaw puzzle. All these pieces of the jigsaw are to be assembled into an image and that's how neural networks work for computer vision. They distinguish many different pieces of the image, they identify the edges and then model the subcomponents. Using filtering and a series of actions through deep network layers, they can piece all the parts of the image together. the computer is often fed hundreds or thousands of related images for training and recognizing specific objects. <u>𝑨𝑷𝑷𝑳𝑰𝑪𝑨𝑻𝑰𝑶𝑵 𝑶𝑭 𝑪𝑶𝑴𝑷𝑼𝑻𝑬𝑹 𝑽𝑰𝑺𝑰𝑶𝑵:</u> <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > Computer Vision for Defect Detection <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5"/ > Computer Vision for Intruder Detection <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5"/ > Computer Vision for Screen Reader <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5" / > Computer Vision for Code and Character Reader (OCR) <img src="http://drive.google.com/uc?export=view&id=1NB7WNOSYxqritGe2-4xzNC5wVEeayxTb" width="46" height="42" align = "left" HSPACE="20" VSPACE="5"/ > Computer Vision in robotics for Bin Picking <style> div { text-align: justify; text-justify: inter-word; } </style>

Trending Discussions on Computer Vision

    How to compare list of dicts with list in python
    Keras ImageDataGenerator validation_split does not split validation data as expected
    Find box in the image and save as an image cv2
    Camera calibration, focal length value seems too large
    how can reslove : InvalidArgumentError: Graph execution error?
    Specific options missing in keras layer class
    What Type of Computer Vision Task is This?
    Normalization before and after Albumentations augmentations?
    Google cloud object detection model training error
    Determine if certain parts of an RGB image are colored or grayscale using numpy

QUESTION

How to compare list of dicts with list in python

Asked 2022-Apr-15 at 10:36

I am working on a computer vision project where the model is predicting the objects in the frame. I am appending all the objects in a list detectedObjs. I have to create a list of dicts for these detected objects which will contain the name, start time and end time of the object. Start time basically means when the object was first detected and end time means when the object was last detected. So for this I have below code:

1for obj in detectedObjs:
2    if not objList:
3        # First object is detected, save its information
4        tmp = dict()
5        tmp['Name'] = obj
6        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
7        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
8        objList.append(tmp)    
9    else:
10        # Here check if the object is alreay present in objList
11        # If yes, then keep updating end time
12        # If no, then add the object information in objList
13        for objDict in objList:
14            if objDict['Name'] == obj:
15                objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
16                break 
17            else:
18                tmp = dict()
19                tmp['Name'] = obj
20                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
21                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
22                objList.append(tmp)   
23

So first in for loop I am saving the information of the first detected object. After that in else, I am checking if the current object is already added in objList, if yes then keep updating the end time otherwise, add it in objList.

The detectedObjs list have item1 and then after few secs item2 is also added. But in the output of objList I can see item1 properly added but item2 is added lot many times. Is there any way to optimize this code so that I can have proper start and end times. Thanks

Below is the full reproducible code. I cannot put the code of prediction from the model here so I have added a thread which will keep on adding items to detectedObj list

1for obj in detectedObjs:
2    if not objList:
3        # First object is detected, save its information
4        tmp = dict()
5        tmp['Name'] = obj
6        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
7        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
8        objList.append(tmp)    
9    else:
10        # Here check if the object is alreay present in objList
11        # If yes, then keep updating end time
12        # If no, then add the object information in objList
13        for objDict in objList:
14            if objDict['Name'] == obj:
15                objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
16                break 
17            else:
18                tmp = dict()
19                tmp['Name'] = obj
20                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
21                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
22                objList.append(tmp)   
23from threading import Thread
24import datetime
25import time
26
27detectedObjs = []
28
29def doJob():
30    global detectedObjs
31    for i in range(2):
32        if i == 0:
33            detectedObjs.append(&quot;item1&quot;)
34        elif i == 1:
35            detectedObjs.append(&quot;item2&quot;)
36        elif i == 2:
37            detectedObjs.append(&quot;item3&quot;)
38        elif i == 3:
39            detectedObjs.remove(&quot;item1&quot;)
40        elif i == 4:
41            detectedObjs.remove(&quot;item2&quot;)
42        elif i == 5:
43            detectedObjs.remove(&quot;item3&quot;)
44        time.sleep(3)
45
46Thread(target=doJob).start()
47while True:
48    objList = []
49    for obj in detectedObjs:
50        if not objList:
51            # First object is detected, save its information
52            tmp = dict()
53            tmp['Name'] = obj
54            tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
55            tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
56            objList.append(tmp)
57        else:
58            # Here check if the object is alreay present in objList
59            # If yes, then keep updating end time
60            # If no, then add the object information in objList
61            for objDict in objList:
62                if objDict['Name'] == obj:
63                    objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
64                    break
65                else:
66                    tmp = dict()
67                    tmp['Name'] = obj
68                    tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
69                    tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
70                    objList.append(tmp)
71    print(objList)
72

ANSWER

Answered 2022-Apr-15 at 10:36

I would recommend you use a dict containing dicts… here is an untested version of your code…

copy icondownload icon

1for obj in detectedObjs:
2    if not objList:
3        # First object is detected, save its information
4        tmp = dict()
5        tmp['Name'] = obj
6        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
7        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
8        objList.append(tmp)    
9    else:
10        # Here check if the object is alreay present in objList
11        # If yes, then keep updating end time
12        # If no, then add the object information in objList
13        for objDict in objList:
14            if objDict['Name'] == obj:
15                objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
16                break 
17            else:
18                tmp = dict()
19                tmp['Name'] = obj
20                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
21                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
22                objList.append(tmp)   
23from threading import Thread
24import datetime
25import time
26
27detectedObjs = []
28
29def doJob():
30    global detectedObjs
31    for i in range(2):
32        if i == 0:
33            detectedObjs.append(&quot;item1&quot;)
34        elif i == 1:
35            detectedObjs.append(&quot;item2&quot;)
36        elif i == 2:
37            detectedObjs.append(&quot;item3&quot;)
38        elif i == 3:
39            detectedObjs.remove(&quot;item1&quot;)
40        elif i == 4:
41            detectedObjs.remove(&quot;item2&quot;)
42        elif i == 5:
43            detectedObjs.remove(&quot;item3&quot;)
44        time.sleep(3)
45
46Thread(target=doJob).start()
47while True:
48    objList = []
49    for obj in detectedObjs:
50        if not objList:
51            # First object is detected, save its information
52            tmp = dict()
53            tmp['Name'] = obj
54            tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
55            tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
56            objList.append(tmp)
57        else:
58            # Here check if the object is alreay present in objList
59            # If yes, then keep updating end time
60            # If no, then add the object information in objList
61            for objDict in objList:
62                if objDict['Name'] == obj:
63                    objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
64                    break
65                else:
66                    tmp = dict()
67                    tmp['Name'] = obj
68                    tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
69                    tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
70                    objList.append(tmp)
71    print(objList)
72obj_dict = {}
73for obj in detectedObjs:
74    if obj not in obj_dict:  # checks the keys for membership
75        # first entry
76        time_seen = datetime.datetime.utcnow().isoformat()
77        obj_dict[obj] = {
78            “name”: obj,
79            “start”: time_seen,
80            “end”: time_seen,
81        }
82    else:  # additional time(s) seen
83        time_seen = datetime.datetime.utcnow().isoformat()
84        obj_dict[obj][“end”] = time_seen
85

Additionally this will save on processing as your list grows larger, it won’t have to search the whole list for an entry each time to update it.

Source https://stackoverflow.com/questions/71882253

Community Discussions contain sources that include Stack Exchange Network

    How to compare list of dicts with list in python
    Keras ImageDataGenerator validation_split does not split validation data as expected
    Find box in the image and save as an image cv2
    Camera calibration, focal length value seems too large
    how can reslove : InvalidArgumentError: Graph execution error?
    Specific options missing in keras layer class
    What Type of Computer Vision Task is This?
    Normalization before and after Albumentations augmentations?
    Google cloud object detection model training error
    Determine if certain parts of an RGB image are colored or grayscale using numpy

QUESTION

How to compare list of dicts with list in python

Asked 2022-Apr-15 at 10:36

I am working on a computer vision project where the model is predicting the objects in the frame. I am appending all the objects in a list detectedObjs. I have to create a list of dicts for these detected objects which will contain the name, start time and end time of the object. Start time basically means when the object was first detected and end time means when the object was last detected. So for this I have below code:

1for obj in detectedObjs:
2    if not objList:
3        # First object is detected, save its information
4        tmp = dict()
5        tmp['Name'] = obj
6        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
7        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
8        objList.append(tmp)    
9    else:
10        # Here check if the object is alreay present in objList
11        # If yes, then keep updating end time
12        # If no, then add the object information in objList
13        for objDict in objList:
14            if objDict['Name'] == obj:
15                objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
16                break 
17            else:
18                tmp = dict()
19                tmp['Name'] = obj
20                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
21                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
22                objList.append(tmp)   
23

So first in for loop I am saving the information of the first detected object. After that in else, I am checking if the current object is already added in objList, if yes then keep updating the end time otherwise, add it in objList.

The detectedObjs list have item1 and then after few secs item2 is also added. But in the output of objList I can see item1 properly added but item2 is added lot many times. Is there any way to optimize this code so that I can have proper start and end times. Thanks

Below is the full reproducible code. I cannot put the code of prediction from the model here so I have added a thread which will keep on adding items to detectedObj list

1for obj in detectedObjs:
2    if not objList:
3        # First object is detected, save its information
4        tmp = dict()
5        tmp['Name'] = obj
6        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
7        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
8        objList.append(tmp)    
9    else:
10        # Here check if the object is alreay present in objList
11        # If yes, then keep updating end time
12        # If no, then add the object information in objList
13        for objDict in objList:
14            if objDict['Name'] == obj:
15                objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
16                break 
17            else:
18                tmp = dict()
19                tmp['Name'] = obj
20                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
21                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
22                objList.append(tmp)   
23from threading import Thread
24import datetime
25import time
26
27detectedObjs = []
28
29def doJob():
30    global detectedObjs
31    for i in range(2):
32        if i == 0:
33            detectedObjs.append(&quot;item1&quot;)
34        elif i == 1:
35            detectedObjs.append(&quot;item2&quot;)
36        elif i == 2:
37            detectedObjs.append(&quot;item3&quot;)
38        elif i == 3:
39            detectedObjs.remove(&quot;item1&quot;)
40        elif i == 4:
41            detectedObjs.remove(&quot;item2&quot;)
42        elif i == 5:
43            detectedObjs.remove(&quot;item3&quot;)
44        time.sleep(3)
45
46Thread(target=doJob).start()
47while True:
48    objList = []
49    for obj in detectedObjs:
50        if not objList:
51            # First object is detected, save its information
52            tmp = dict()
53            tmp['Name'] = obj
54            tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
55            tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
56            objList.append(tmp)
57        else:
58            # Here check if the object is alreay present in objList
59            # If yes, then keep updating end time
60            # If no, then add the object information in objList
61            for objDict in objList:
62                if objDict['Name'] == obj:
63                    objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
64                    break
65                else:
66                    tmp = dict()
67                    tmp['Name'] = obj
68                    tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
69                    tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
70                    objList.append(tmp)
71    print(objList)
72

ANSWER

Answered 2022-Apr-15 at 10:36

I would recommend you use a dict containing dicts… here is an untested version of your code…

copy icondownload icon

1for obj in detectedObjs:
2    if not objList:
3        # First object is detected, save its information
4        tmp = dict()
5        tmp['Name'] = obj
6        tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
7        tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
8        objList.append(tmp)    
9    else:
10        # Here check if the object is alreay present in objList
11        # If yes, then keep updating end time
12        # If no, then add the object information in objList
13        for objDict in objList:
14            if objDict['Name'] == obj:
15                objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
16                break 
17            else:
18                tmp = dict()
19                tmp['Name'] = obj
20                tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
21                tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
22                objList.append(tmp)   
23from threading import Thread
24import datetime
25import time
26
27detectedObjs = []
28
29def doJob():
30    global detectedObjs
31    for i in range(2):
32        if i == 0:
33            detectedObjs.append(&quot;item1&quot;)
34        elif i == 1:
35            detectedObjs.append(&quot;item2&quot;)
36        elif i == 2:
37            detectedObjs.append(&quot;item3&quot;)
38        elif i == 3:
39            detectedObjs.remove(&quot;item1&quot;)
40        elif i == 4:
41            detectedObjs.remove(&quot;item2&quot;)
42        elif i == 5:
43            detectedObjs.remove(&quot;item3&quot;)
44        time.sleep(3)
45
46Thread(target=doJob).start()
47while True:
48    objList = []
49    for obj in detectedObjs:
50        if not objList:
51            # First object is detected, save its information
52            tmp = dict()
53            tmp['Name'] = obj
54            tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
55            tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
56            objList.append(tmp)
57        else:
58            # Here check if the object is alreay present in objList
59            # If yes, then keep updating end time
60            # If no, then add the object information in objList
61            for objDict in objList:
62                if objDict['Name'] == obj:
63                    objDict[&quot;EndTime&quot;] = datetime.datetime.utcnow().isoformat()
64                    break
65                else:
66                    tmp = dict()
67                    tmp['Name'] = obj
68                    tmp['StartTime'] = datetime.datetime.utcnow().isoformat()
69                    tmp['EndTime'] = datetime.datetime.utcnow().isoformat()
70                    objList.append(tmp)
71    print(objList)
72obj_dict = {}
73for obj in detectedObjs:
74    if obj not in obj_dict:  # checks the keys for membership
75        # first entry
76        time_seen = datetime.datetime.utcnow().isoformat()
77        obj_dict[obj] = {
78            “name”: obj,
79            “start”: time_seen,
80            “end”: time_seen,
81        }
82    else:  # additional time(s) seen
83        time_seen = datetime.datetime.utcnow().isoformat()
84        obj_dict[obj][“end”] = time_seen
85

Additionally this will save on processing as your list grows larger, it won’t have to search the whole list for an entry each time to update it.

Source https://stackoverflow.com/questions/71882253