python获取指定区域的像素_如何将图像的所有像素值转换为特定范围-python

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.

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].

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值