首页 > 编程知识 正文

用python实现颜色识别功能的简单介绍

时间:2023-12-24 12:05:25 阅读:320238 作者:XYWJ

本文目录一览:

用python写识别图片主要颜色的程序

# -*- coding: utf-8 -*-

import colorsys

 

def get_dominant_color(image):

    

    #颜色模式转换,以便输出rgb颜色值

    image = image.convert('RGBA')

    

    #生成缩略图,减少计算量,减小cpu压力

    image.thumbnail((200, 200))

    

    max_score = None

    dominant_color = None

    

    for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):

        # 跳过纯黑色

        if a == 0:

            continue

        

        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]

       

        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072)  13, 235)

       

        y = (y - 16.0) / (235 - 16)

        

        # 忽略高亮色

        if y  0.9:

            continue

        

        # Calculate the score, preferring highly saturated colors.

        # Add 0.1 to the saturation so we don't completely ignore grayscale

        # colors by multiplying the count by zero, but still give them a low

        # weight.

        score = (saturation + 0.1) * count

        

        if score  max_score:

            max_score = score

            dominant_color = (r, g, b)

    

    return dominant_color

    

if __name__=="__main__":

    from PIL import Image

    import os

    

    path = r'.\pics\'

    fp = open('file_color.txt','w')

    for filename in os.listdir(path):

        print path+filename

        try:

            color =  get_dominant_color(Image.open(path+filename))

            fp.write('The color of '+filename+' is '+str(color)+'n')

        except:

            print "This file format is not support"

    fp.close()

pics文件夹和python程序在一个目录下,产生的文件名file_color.txt也在这个目录下。

看看能否帮到你

如何用python将文件夹中图片根据颜色分类

本文实例讲述了Python通过PIL获取图片主要颜色并和颜色库进行对比的方法。分享给大家供大家参考。具体分析如下:

这段代码主要用来从图片提取其主要颜色,类似Goolge和Baidu的图片搜索时可以指定按照颜色搜索,所以我们先需要将每张图片的主要颜色提取出来,然后将颜色划分到与其最接近的颜色段上,然后就可以按照颜色搜索了。

在使用google或者baidu搜图的时候会发现有一个图片颜色选项,感觉非常有意思,有人可能会想这肯定是人为的去划分的,呵呵,有这种可能,但是估计人会累死,开个玩笑,当然是通过机器识别的,海量的图片只有机器识别才能做到。

那用python能不能实现这种功能呢?答案是:能

利用python的PIL模块的强大的图像处理功能就可以做到,下面上代码: 

复制代码代码如下:

import colorsys

def get_dominant_color(image):

#颜色模式转换,以便输出rgb颜色值

image = image.convert('RGBA')

#生成缩略图,减少计算量,减小cpu压力

image.thumbnail((200, 200))

max_score = None

dominant_color = None

for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):

# 跳过纯黑色

if a == 0:

continue

saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]

y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) 13, 235)

y = (y - 16.0) / (235 - 16)

# 忽略高亮色

if y 0.9:

continue

# Calculate the score, preferring highly saturated colors.

# Add 0.1 to the saturation so we don't completely ignore grayscale

# colors by multiplying the count by zero, but still give them a low

# weight.

score = (saturation + 0.1) * count

if score max_score:

max_score = score

dominant_color = (r, g, b)

return dominant_color

使用方法:

from PIL import Image

print get_dominant_color(Image.open('logo.jpg'))

这样就会返回一个rgb颜色,但是这个值是很精确的范围,那我们如何实现百度图片那样的色域呢??

其实方法很简单,r/g/b都是0-255的值,我们只要把这三个值分别划分相等的区间,然后组合,取近似值。例如:划分为0-127,和128-255,然后自由组合,可以出现八种组合,然后从中挑出比较有代表性的颜色即可。

当然我只是举一个例子,你也可以划分的更细,那样显示的颜色就会更准确~~大家赶快试试吧

怎样使用Python图像处理

Python图像处理是一种简单易学,功能强大的解释型编程语言,它有简洁明了的语法,高效率的高层数据结构,能够简单而有效地实现面向对象编程,下文进行对Python图像处理进行说明。

当然,首先要感谢“恋花蝶”,是他的文章“用Python图像处理 ” 帮我坚定了用Python和PIL解决问题的想法,对于PIL的一些介绍和基本操作,可以看看这篇文章。我这里主要是介绍点我在使用过程中的经验。

PIL可以对图像的颜色进行转换,并支持诸如24位彩色、8位灰度图和二值图等模式,简单的转换可以通过Image.convert(mode)函数完 成,其中mode表示输出的颜色模式。例如''L''表示灰度,''1''表示二值图模式等。

但是利用convert函数将灰度图转换为二值图时,是采用固定的阈 值127来实现的,即灰度高于127的像素值为1,而灰度低于127的像素值为0。为了能够通过自定义的阈值实现灰度图到二值图的转换,就要用到 Image.point函数。

深度剖析Python语法功能

深度说明Python应用程序特点

对Python数据库进行学习研究

Python开发人员对Python经验之谈

对Python动态类型语言解析

Image.point函数有多种形式,这里只讨论Image.point(table, mode),利用该函数可以通过查表的方式实现像素颜色的模式转换。其中table为颜色转换过程中的映射表,每个颜色通道应当有256个元素,而 mode表示所输出的颜色模式,同样的,''L''表示灰度,''1''表示二值图模式。

可见,转换过程的关键在于设计映射表,如果只是需要一个简单的箝位值,可以将table中高于或低于箝位值的元素分别设为1与0。当然,由于这里的table并没有什么特殊要求,所以可以通过对元素的特殊设定实现(0, 255)范围内,任意需要的一对一映射关系。

示例代码如下:

import Image # load a color image im = Image.open(''fun.jpg'') # convert to grey level image Lim = im.convert(''L'') Lim.save(''fun_Level.jpg'') # setup a converting table with constant threshold threshold = 80 table = [] for i in range(256): if i threshold: table.append(0) else: table.append(1) # convert to binary image by the table bim = Lim.point(table, ''1'') bim.save(''fun_binary.jpg'')

IT部分通常要完成的任务相当繁重但支撑这些工作的资源却很少,这已经成为公开的秘密。任何承诺提高编码效率、降低软件总成本的IT解决方案都应该进行 周到的考虑。Python图像处理所具有的一个显著优势就是可以在企业的软件创建和维护阶段节约大量资金,而这两个阶段的软件成本占到了软件整个生命周期中总成本 的50%到95%。

Python清晰可读的语法使得软件代码具有异乎寻常的易读性,甚至对那些不是最初接触和开发原始项目的程序员都 能具有这样的强烈感觉。虽然某些程序员反对在Python代码中大量使用空格。

不过,几乎人人都承认Python图像处理的可读性远胜于C或者Java,后两 者都采用了专门的字符标记代码块结构、循环、函数以及其他编程结构的开始和结束。提倡Python的人还宣称,采用这些字符可能会产生显著的编程风格差 异,使得那些负责维护代码的人遭遇代码可读性方面的困难。转载

opencv对图像的颜色识别问题,要用python2实现

我没用过Python的Opencv的库,只是用过Python的Image的库;Image库已经可以结果这个问题了

我试着做一下:你先得安装PIL库

得到rgb三个通道,然后转到HSV通道,其中H表示0-255的颜色,V表示强度,你大概先知道紫色的范围是多少

from PIL import Image

import colorsys

def CalculateH(img):

    if len(img.getbands()) == 4:

        ir,ig,ib,ia = img.split()

    else:

        ir, ig, ib = img.split()

    

    Hdat = []

    Sdat = []

    Vdat = []    

    

    for rd,gn,bl in zip(ir.getdata(),ig.getdata(),ib.getdata()):

        h,l,s = colorsys.rgb_to_hsv(rd/255.,gn/255.,bl/255.)

        Hdat.append(h)

        Sdat.append(l)

        Vdat.append(s)

    meanV = mean(Vdat)

    return Hdat, meanV

    

def myreadim(filename):

    im = Image.open(filename)

    H,V = CalculateH(im)

后面我就懒得写了,应该思路都清楚了吧,要转到其他的颜色通道上,不要在rgb通道上

用python K值聚类识别图片主要颜色的程序,算法python代码已经有了

难得被人求助一次, 这个必须回答一下. 不过你的需求确实没有写得太清楚. 根据k值算法出来的是主要颜色有三个, 所以我把三个颜色都打在记事本里了. 如果和你的需求有误, 请自行解决吧.

另外这里需要用到numpy的库, 希望你装了, 如果没装, 这个直接安装也比较麻烦, 可以看一下portablepython的绿色版。

代码如下:

# -*- coding: utf-8 -*-

import Image

import random

import numpy

class Cluster(object):

    def __init__(self):

        self.pixels = []

        self.centroid = None

    def addPoint(self, pixel):

        self.pixels.append(pixel)

    def setNewCentroid(self):

        R = [colour[0] for colour in self.pixels]

        G = [colour[1] for colour in self.pixels]

        B = [colour[2] for colour in self.pixels]

        R = sum(R) / len(R)

        G = sum(G) / len(G)

        B = sum(B) / len(B)

        self.centroid = (R, G, B)

        self.pixels = []

        return self.centroid

class Kmeans(object):

    def __init__(self, k=3, max_iterations=5, min_distance=5.0, size=200):

        self.k = k

        self.max_iterations = max_iterations

        self.min_distance = min_distance

        self.size = (size, size)

    def run(self, image):

        self.image = image

        self.image.thumbnail(self.size)

        self.pixels = numpy.array(image.getdata(), dtype=numpy.uint8)

        self.clusters = [None for i in range(self.k)]

        self.oldClusters = None

        randomPixels = random.sample(self.pixels, self.k)

        for idx in range(self.k):

            self.clusters[idx] = Cluster()

            self.clusters[idx].centroid = randomPixels[idx]

        iterations = 0

        while self.shouldExit(iterations) is False:

            self.oldClusters = [cluster.centroid for cluster in self.clusters]

            print iterations

            for pixel in self.pixels:

                self.assignClusters(pixel)

            for cluster in self.clusters:

                cluster.setNewCentroid()

            iterations += 1

        return [cluster.centroid for cluster in self.clusters]

    def assignClusters(self, pixel):

        shortest = float('Inf')

        for cluster in self.clusters:

            distance = self.calcDistance(cluster.centroid, pixel)

            if distance  shortest:

                shortest = distance

                nearest = cluster

        nearest.addPoint(pixel)

    def calcDistance(self, a, b):

        result = numpy.sqrt(sum((a - b) ** 2))

        return result

    def shouldExit(self, iterations):

        if self.oldClusters is None:

            return False

        for idx in range(self.k):

            dist = self.calcDistance(

                numpy.array(self.clusters[idx].centroid),

                numpy.array(self.oldClusters[idx])

            )

            if dist  self.min_distance:

                return True

        if iterations = self.max_iterations:

            return False

        return True

    # ############################################

    # The remaining methods are used for debugging

    def showImage(self):

        self.image.show()

    def showCentroidColours(self):

        for cluster in self.clusters:

            image = Image.new("RGB", (200, 200), cluster.centroid)

            image.show()

    def showClustering(self):

        localPixels = [None] * len(self.image.getdata())

        for idx, pixel in enumerate(self.pixels):

                shortest = float('Inf')

                for cluster in self.clusters:

                    distance = self.calcDistance(

                        cluster.centroid,

                        pixel

                    )

                    if distance  shortest:

                        shortest = distance

                        nearest = cluster

                localPixels[idx] = nearest.centroid

        w, h = self.image.size

        localPixels = numpy.asarray(localPixels)

            .astype('uint8')

            .reshape((h, w, 3))

        colourMap = Image.fromarray(localPixels)

        colourMap.show()

    

if __name__=="__main__":

    from PIL import Image

    import os

    

    k_image=Kmeans()

    path = r'.\pics\'

    fp = open('file_color.txt','w')

    for filename in os.listdir(path):

        print path+filename

        try:

            color = k_image.run(Image.open(path+filename))

            fp.write('The color of '+filename+' is '+str(color)+'n')

        except:

            print "This file format is not support"

    fp.close()

提取HSV颜色特征,并计算维数的熵,最后保存特征和熵,形式:图像名、特征和熵,用python实现,怎么实现

可以使用Python版的opencv 来实现。

现读取图片:

import cv2

import numpy as np

from matplotlib import pyplot as plt

image=cv2.imread('./src/q5.png')

HSV=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)

计算熵

img = np.array(HSV)

for i in range(len(img)):

    for j in range(len(img[i])):

        val = img[i][j]

        tmp[val] = float(tmp[val] + 1)

        k =  float(k + 1)

for i in range(len(tmp)):

    tmp[i] = float(tmp[i] / k)

for i in range(len(tmp)):

    if(tmp[i] == 0):

        res = res

    else:

        res = float(res - tmp[i] * (math.log(tmp[i]) / math.log(2.0)))

保存:

HSV图形可以直接存储,特征可以存xml中~

cv2.imwrite("具体路径",HSV)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。