Untitled
unknown
plain_text
a year ago
2.6 kB
8
Indexable
class TrashClassifier:
_instance = None
_camera = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(TrashClassifier, cls).__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
if self._initialized:
return
self.client = OpenAI()
if not TrashClassifier._camera:
try:
TrashClassifier._camera = Picamera2()
TrashClassifier._camera.start()
time.sleep(2) # Give camera time to warm up
except Exception as e:
print(f"Error initializing camera: {e}")
TrashClassifier._camera = None
if not os.path.exists('img'):
os.makedirs('img')
self._initialized = True
def take_picture(self):
if not TrashClassifier._camera:
raise Exception("Camera not initialized")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
image_path = f"img/capture_{timestamp}.jpg"
TrashClassifier._camera.capture_file(image_path)
return image_path
def encode_image(self, image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def classify_image(self, image_path):
base64_image = self.encode_image(image_path)
response = self.client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "In which german recycling bin does the object in the image belong: Gelber Sack, Biomüll, Papier, Restmüll. output just the bin without . or anything else"
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
]
)
return response.choices[0].message.content.strip()
@classmethod
def cleanup(cls):
if cls._camera:
cls._camera.stop()
cls._camera = NoneEditor is loading...
Leave a Comment