使用Python / PIL检测HSV颜色空间(来自RGB)的阈值 [英] Detecting thresholds in HSV color space (from RGB) using Python / PIL

查看:3686
本文介绍了使用Python / PIL检测HSV颜色空间(来自RGB)的阈值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拍摄RGB图像并将其转换为黑白RGB图像,如果其HSV值介于某个范围之间,则像素为黑色,否则为白色。

I want to take an RGB image and convert it to a black and white RGB image, where a pixel is black if its HSV value is between a certain range and white otherwise.

目前我创建了一个新图像,然后通过迭代其数据创建一个新的像素值列表,然后 .putdata()该列表以形成新图像。

Currently I create a new image, then create a list of new pixel values by iterating through its data, then .putdata() that list to form the new image.

感觉应该有更快的方法来做到这一点,例如使用 .point(),但似乎 .point()没有得到给定的像素,但值从0到而是255。是否有 .point()转换但是在像素上?

It feels like there should be a much faster way of doing this, e.g. with .point(), but it seems .point() doesn't get given pixels but values from 0 to 255 instead. Is there a .point() transform but on pixels?

推荐答案

好的,这个 工作(修复了一些溢出错误):

Ok, this does work (fixed some overflow errors):

import numpy, Image
i = Image.open(fp).convert('RGB')
a = numpy.asarray(i, int)

R, G, B = a.T

m = numpy.min(a,2).T
M = numpy.max(a,2).T

C = M-m #chroma
Cmsk = C!=0

# Hue
H = numpy.zeros(R.shape, int)
mask = (M==R)&Cmsk
H[mask] = numpy.mod(60*(G-B)/C, 360)[mask]
mask = (M==G)&Cmsk
H[mask] = (60*(B-R)/C + 120)[mask]
mask = (M==B)&Cmsk
H[mask] = (60*(R-G)/C + 240)[mask]
H *= 255
H /= 360 # if you prefer, leave as 0-360, but don't convert to uint8

# Value
V = M

# Saturation
S = numpy.zeros(R.shape, int)
S[Cmsk] = ((255*C)/V)[Cmsk]

# H, S, and V are now defined as integers 0-255

它基于维基百科对 HSV 的定义。随着时间的推移,我会仔细研究一下。肯定有加速和错误。如果您发现任何问题,请告诉我。欢呼。

It is based on the Wikipedia's definition of HSV. I'll look it over as I get more time. There are definitely speedups and maybe bugs. Please let me know if you find any. cheers.

结果:

从这个色轮开始:

starting with this colorwheel:

I得到以下结果:

Hue:

值:

饱和度:

这篇关于使用Python / PIL检测HSV颜色空间(来自RGB)的阈值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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