Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

image - Detecting thresholds in HSV color space (from RGB) using Python / PIL

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.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


Results:

starting with this colorwheel: enter image description here

I get these results:

Hue:

enter image description here

Value:

enter image description here

Saturation:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...