Skip to content

Instantly share code, notes, and snippets.

@ilikerobots
Created March 28, 2022 06:46
Show Gist options
  • Save ilikerobots/fb31d273c708d4030cdf94fcbf4da6ce to your computer and use it in GitHub Desktop.
Save ilikerobots/fb31d273c708d4030cdf94fcbf4da6ce to your computer and use it in GitHub Desktop.
Django Image model with Average Color field
from decimal import Decimal
from django.db import models
class Color(models.Model):
red = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=12)
green = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=12)
blue = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=12)
alpha = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=12, default=Decimal(1.0))
def __str__(self):
return f'({self.red}, {self.green}, {self.blue})'
class Image(models.Model):
name = models.CharField(max_length=64, blank=True, null=True)
average_color = models.OneToOneField(Color, null=True, blank=True, on_delete=models.SET_NULL)
def __str__(self):
return f'{self.name}: {self.average_color}'
from color.models import *
Image.objects.create(name="Mountain", average_color=Color.objects.create(red=Decimal(0.295), green=Decimal(0.303), blue=Decimal(0.3)))
Image.objects.create(name="Sea", average_color=Color.objects.create(red=Decimal(0.145), green=Decimal(0.30), blue=Decimal(0.6)))
Image.objects.create(name="Sky", average_color=Color.objects.create(red=Decimal(0.3), green=Decimal(0.297), blue=Decimal(0.31)))
target_color = Color(red=Decimal(0.3), green=Decimal(0.3), blue=Decimal(0.3))
search_tolerance = Decimal(0.02)
matched_images = Image.objects.filter(
average_color__red__gte=target_color.red - search_tolerance,
average_color__red__lte=target_color.red + search_tolerance,
average_color__green__gte=target_color.green - search_tolerance,
average_color__green__lte=target_color.green + search_tolerance,
average_color__blue__gte=target_color.blue - search_tolerance,
average_color__blue__lte=target_color.blue + search_tolerance
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment