Django从ImageField获取模式

2024-06-23 19:10:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出保存图像时的模式

我有一个这样的模型:

class Model(models.Model):
    image = models.ImageField()

    def save(self, *args, **kwargs):
        self.create_dominant_color()
        super().save(*args, **kwargs)

    def create_dominant_color(self):
        color = get_dominant_color(self.image)
        self.dominant_color = color

这是我的主要颜色(来自https://stackoverflow.com/a/34964548/9878135):

def get_dominant_color(image_file):
    im = Image.new(image_file.mode, (150, 150))
    ar = scipy.misc.fromimage(im)
    shape = ar.shape
    ar = ar.reshape(scipy.product(shape[:2]), shape[2])

    codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)

    vecs, dist = scipy.cluster.vq.vq(ar, codes)  # assign codes
    counts, bins = scipy.histogram(vecs, len(codes))  # count occurrences

    index_max = scipy.argmax(counts)  # find most frequent
    peak = codes[index_max]
    colour = "#" + ''.join(chr(c) for c in peak).encode('hex')
    return colour

当我尝试访问image_file.mode时,出现以下错误:

AttributeError: 'ImageCacheFile' object has no attribute 'mode'

我试着把self.image改成self.image.open()self.image.read(),但它们都没有mode属性。有没有办法得到模式?还是有解决办法


Tags: imageselfmodelmodemodelsdef模式scipy

热门问题