如何将图像的所有像素值转换为特定范围-python [英] How to Convert all pixel values of an image to a certain range -python

查看:573
本文介绍了如何将图像的所有像素值转换为特定范围-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有12种不同颜色的rgb图像,但是我事先不知道颜色(像素值).我想转换所有介于0和11之间的像素值,每个像素值都代表原始rgb图像的唯一颜色.

I have an rgb image with 12 distinct colours but I do not know the colours (pixel values) beforehand. I want to convert all the pixel values between 0 and 11,each symbolising a unique colour of the original rgb image.

例如全部[230,100,140]转换为[0,0,0],全部[130,90,100]转换为[0,0,1],依此类推...全部[210,80,50]转换为[0,0, 11].

e.g. all [230,100,140] converted to [0,0,0] , all [130,90,100] converted to [0,0,1] and so on ...all [210,80,50] converted to [0,0,11].

推荐答案

快速而肮脏的应用程序.可以改进很多,尤其是逐像素遍历整个图像不是很麻木,也不是很opencv,但是我懒得记住确切的阈值和替换RGB像素的方法.

Quick and dirty application. Much can be improved, especially going through the whole image pixel by pixel is not very numpy nor very opencv, but I was too lazy to remember exactly how to threshold and replace RGB pixels..

import cv2
import numpy as np

#finding unique rows
#comes from this answer : http://stackoverflow.com/questions/8560440/removing-duplicate-columns-and-rows-from-a-numpy-2d-array
def unique_rows(a):
    a = np.ascontiguousarray(a)
    unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1]))
    return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))

img=cv2.imread(your_image)

#listing all pixels
pixels=[]
for p in img:
    for k in p:
        pixels.append(k)

#finding all different colors
colors=unique_rows(pixels)

#comparing each color to every pixel
res=np.zeros(img.shape)
cpt=0
for color in colors:
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            if (img[i,j,:]==color).all(): #if pixel is this color
                res[i,j,:]=[0,0,cpt] #set the pixel to [0,0,counter]
    cpt+=1

这篇关于如何将图像的所有像素值转换为特定范围-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆