Untitled

 avatar
unknown
plain_text
5 months ago
2.9 kB
3
Indexable
def classify_image(self, image_path):
    try:
        print("\n=== Starting Image Classification ===")
        
        # Check internet connection
        has_internet = self.check_internet_connection()
        print(f"Internet connection: {'Available' if has_internet else 'Not available'}")
        
        root = next(iter(CircularProgress._instances)).winfo_toplevel()
        language = getattr(root, 'LANGUAGE', 'EN')
        
        if has_internet:
            # Use OpenAI Vision API
            print("Using online classification (OpenAI)")
            base64_image = self.encode_image(image_path)
            prompt = self.bin_config.get_ai_prompt(language)
            print("Prompt:", prompt)
            
            response = self.client.chat.completions.create(
                model="gpt-4-vision-preview",
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": f"data:image/jpeg;base64,{base64_image}"
                                }
                            }
                        ]
                    }
                ]
            )
            result = response.choices[0].message.content.strip()
            
        else:
            # Use Edge Impulse local model
            print("Using offline classification (Edge Impulse)")
            if not self.edge_impulse:
                raise Exception("Edge Impulse model not initialized")
                
            # Read and classify the image
            print("Reading image from:", image_path)
            image = cv2.imread(image_path)
            if image is None:
                raise Exception("Failed to read image")
                
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            print("Running classification...")
            predictions = self.edge_impulse.classify_image(image_rgb)
            print("Raw predictions:", predictions)
            
            # Get the predicted class
            max_index = np.argmax(predictions)
            result = self.edge_impulse.class_names[max_index]
        
        print(f"Classification result: {result}")
        
        # Find the matching bin ID
        bin_id = self.bin_config.get_bin_id_by_name(result)
        if bin_id:
            print(f"Matched bin ID: {bin_id}")
        
        return result
        
    except Exception as e:
        print(f"\n!!! Error during classification: {str(e)}")
        traceback.print_exc()  # Print full traceback
        raise
    finally:
        print("=== Classification Complete ===\n")
        self.cleanup_temp_files()
Editor is loading...
Leave a Comment