python convert rgb to hsv

The documentation of colorsys explains that all colour space coordinates are floating point numbers between 0.0 and 1.0 – rescale your values accordingly to get the desired results:

>>> h, s, v = colorsys.rgb_to_hsv(144/255., 190/255., 255/255.)
>>> 360 * h, 100 * s, 100 * v
(215.13513513513513, 43.529411764705884, 100.0)

colorsys.hls_to_rgb(h, l, s)

Convert the color from HLS coordinates to RGB coordinates.

import Imge,colorsys    
LenaImage1 ='lena.png')
r,g,b = LenaImage1.split()
Hdat = []
Ldat = []
Sdat = []    
for rd,gn,bl in zip(r.getdata(),g.getdata(),b.getdata()):
    h,l,s = colorsys.rgb_to_hls(rd/255.,gn/255.,bl/255.)

newimg = Image.merge('RGB',(r,g,b))'lenaHSV.png')

Hue describes the shade of color and where that color it is found in the color spectrum. Red, yellow, and purple are words that describe hue.
Figure 5.3
S. The saturation describes how pure the hue is with respect to a white reference.
S. The saturation describes how pure the hue is with respect to a white reference.  Saturation refers to the dominance of hue in the color. On the outer edge of the hue wheel are the ‘pure’ hues. As you move into the center of the wheel, the hue we are using to describe the color dominates less and less. When you reach the center of the wheel, no hue dominates.
One of the dimensions is lightness-darkness. How light or dark a color is is referred to either as a colors lightness or value.

These colors directly on the central axis are considered desaturated. These desaturated colors constitute the  grayscale; running from white to black with all of the intermediate grays in between.

Saturation, therefore, is the dimension running from the outer edge of the hue wheel (fully saturated) to the center (fully desaturated), perpendicular to the value axis

A horizontal slice of the model shown in Figure 9  creates a disk of the hues running around the perimeter. The farther down the value axis, the more restricted the saturation range (the radius of the disk) is and, therefore, the smaller the disk.

Another way you can slice the HSV model solid is vertically. If you took a slice along the saturation axis at a red hue, it might look something like Figure 10:

Figure 10 – A saturation/value slice of a specific hue in the HSV model

This wedge shows all of the saturation and value variations on this particular red. At the top of the wedge, the lightest red runs from high saturation on the right to white on the left. As you move down the wedge, the reds get darker and the saturation range from right to left gets narrower. We can take this theoretical wedge and actually try and see how many saturation and value variations on this red you can make. It might look something like Figure 11:

Figure 11 – Example saturation and value variations on a single red hue

The goal in Figure 11 was to create even increments of saturation going right to left and even increments of value top to bottom. This judgment was made by your ‘eye’, not by some numeric readout from a color mixing tool. Because you are using your ‘eye’, no one’s wedge would exactly like anyone’s else’s. Notice that the end result in Figure 11 is not a perfect triangle. Though more color squares could have been made for the darker reds, you would not have been able tell the difference in color between them. Similarly, if you removed some of the squares in the lighter value range, you would have to have made bigger steps of saturation to get the full range that you can see.

output of exec($pythonscript $array) 【error】

The print sends the output to the process’ STDOUT stream. That will probably end up being the STDOUT of the PHP process which may be in an Apache log. If you want send that stream and send it to the browser, you will need to capture it.

PHP sends ‘echo’ output to the HTTP stream. Python sends it to STDOUT

When you run PHP from the command line, you’re running a single process, and echo does go to STDOUT. But running on a server, the output has to go to the appropriate HTTP request/response. I can’t be bothered to look into it, but I imagine that the PHP process is probably threaded, serving several concurrent requests per process.

string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() executes the given command .

2>&1 needs to be added in the command to get the complete output.

The exec function just return the last line from the result of the command.

$command = "python ./fmiq_python/ ../portrait/N06242_10.jpg 2>&1"; exec($command,$out);
echo current($out); //Error:Cannot open image database

python 改变当前工作路径:


echo getcwd();
$content = `ls -al`;
echo getcwd()."\n"; //取得当前工作目录


  • 文件名:

// 第一种

$filelen=strpos($filename,’.’) //获取文件名长度
$filename_name=substr($filename, 0, $filelen); //截取文件名
// 第二种

  • 扩展名:

// 第一种
$extendname = array_pop(explode ( ".",$filename));  
// 第二种
$extendname = end(explode(".", $filename));
// 第三种
$file_part  = pathinfo($filename); 
$extendname = $file_part["extension"];


    • end($file)获取到数组最后一个元素,即为文件的后缀名,文件类型。
    • $file[0],得到文件名?//对a.b.c.exe这类文件名,单纯用数组就很难得到理想的结果


$path = "/home/httpd/html/index.php";
$file = basename($path);        // $file is set to "index.php"
$file = basename($path,".php"); // $file is set to "index"
$filepath = "/html/contents.txt";
echo $filepath."中的文件名是:".basename($filepath);

$command = “python ./fmiq_python/ $query_upload_path 2>&1″;


$downloadFileName = basename(end($out));
streamFile($downloadFile_path.$downloadFileName, $downloadFileName,”application/octet-stream”);

【python Image】image processing

打开文件不用担心格式,也不用了解格式,无论什么格式,都只要把文件名丢给 就可以了。


new_img = img.convert(‘L’) //把 img 转换为 256 级灰度图像,

convert() 是图像实例对象的一个方法,接受一个 mode 参数,用以指定一种色彩模式,mode 的取值可以是如下几种:

· 1 (1-bit pixels, black and white, stored with one pixel per byte)
· L (8-bit pixels, black and white)
· P (8-bit pixels, mapped to any other mode using a colour palette)
· RGB (3×8-bit pixels, true colour) 
· RGBA (4×8-bit pixels, true colour with transparency mask)
· CMYK (4×8-bit pixels, colour separation)
· YCbCr (3×8-bit pixels, colour video format)
· I (32-bit signed integer pixels)
· F (32-bit floating point pixels)
1  1位像素,黑和白,存成8位的像素
L  8位像素,黑白
P  8位像素,使用调色板映射到任何其他模式
RGB  3×8位像素,真彩
RGBA  4×8位像素,真彩+透明通道
CMYK  4×8位像素,颜色隔离
YCbCr  3×8位像素,彩色视频格式
I  32位整型像素
F  32位浮点型像素
PIL 还有限制地支持以下几种比较少见的色彩模式:LA (L with alpha), RGBX (true colour with padding) and RGBa (true colour with premultiplied alpha)

下面看一下 mode 为 ‘1’、’L’、’P’时转换出来的图像:
图 2 mode = ‘1’
图 3 mode = ‘L’
图 4 mode = ‘P’
convert() 函数也接受另一个隐含参数 matrix,转换矩阵 matrix 是一个长度为4 或者16 tuple。下例是一个转换 RGB 空间到 CIE XYZ 空间的例子:

    rgb2xyz = (
        0.412453, 0.357580, 0.180423, 0,
        0.212671, 0.715160, 0.072169, 0,
        0.019334, 0.119193, 0.950227, 0 )
    out = im.convert(“RGB”, rgb2xyz)
new_img = StringIO(), img_format, quality=100) # quality来指定生成图片的质量,范围是0~100

ValueError: image has wrong mode

>>> im = im.convert(‘RGB’, rgb2yiq)

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

File “/usr/lib/python2.7/dist-packages/PIL/“, line 685, in convert

im =, data)

ValueError: image has wrong mode

Now, when can you actually compare the images by using the function ImageChops.difference ?

First, both images have to have pixels that can be stored in an unsigned byte.

This is a very common type of image, but this excludes comparison between images even if they are the same mode. So, you cannot compare an image x and y when one or /both/ of them have a mode of: FII;16I;16LI;16BBGR;15,BGR;16BGR;24, or BGR;32. Just to make it clear: it doesn’t matter if both images are in the same mode if they happen to be in one of the modes above, the function will refuse to work.

So, the comparison can be done when the images are in the modes 1PLLARGBRGBARGBX,RGBaCMYK, or YCbCr as long as they have the same number of bands. This means the images don’t have to have the same mode to be compared. For instance, difference(x.convert('CMYK'), x.convert('RGBA')) or difference(x.convert('1'), x.convert('P')) work just fine. Of course this means difference(x.convert('LA'), x.convert('L')), fails. Finally, the resulting image will always have the mode equal to the first image passed to the function.

This is valid at least for the PIL 1.1.7.

16-bit BGR is listed as "BGR;16" and creates a "RGBX" output.

As it says in the PIL documentation you need to look at the file Unpack.c, you’ll find the list near the end of the file.

image_file = image_file.convert('1') # convert image to black and white

>>> import Image
>>> path=’./upload/sketch/20130129_191637.jpg’
>>> im =

>>> im.mode

>>> im2.mode

Convert RGBA color to RGB

  •  RGBA stands for R ed G reen B lue A lpha, incorporates the alpha value into the actual colour result based on an opaque background colour (or ‘matte’ as it’s referred to).

Assuming that 0 is opaque and 255 is transparent, then 255,255,255,127 RGBA with a black matte will result in 127,127,127 RGB value.

PNG is an image format that uses RGBA.

def reduce_opacity(im, opacity):
    """Returns an image with reduced opacity."""
    assert opacity >= 0 and opacity <= 1
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
        im = im.copy()
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    return im
  • RGB模式下,每个图片由三个通道叠加而成,每个模式下为一个灰度图,当有一个调色板来调色的时候,这三张灰度图的叠加即可合成3*8位(每个像素)的一个真彩图片。


【python PHP】call python in PHP

Use system() if the Python script has no output, or if you want the Python script’s output to go directly to the browser.

Use popen() if you want to write data to the Python script’s standard input, or read data from the Python script’s standard output in php.

    • popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
popen('python [参数]', 'r');


  • #当然,这是有解决的办法的,就是windows下转换一下字符的编码,linux不用转换。再来python接收参数的时候肯定也要转换编码了,烦不烦?


  1. cmd命令或者shell命令是有长度限制的,传的参数过长的时候,接收到的参数就不会完整。
  2. 执行shell命令是有危险的,参数里面多乱码

 command injection

escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn’t a known good character, using something like

preg_replace('/[^a-zA-Z0-9]/', '', $str)

Python 2.7.3 install numpy on ubuntu & 【sys.path】

1. Check python version:

$ python –version

Python 2.7.3

2. Go into the python interpreter:

$ python

Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

3. Check numpy installed or not

>>> import numpy

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named numpy

4. install numpy using ‘apt-get’

$ sudo apt-get install python-numpy python-scipy

5. set the sys-path globally

>>> from pprint import pprint as pp
>>> import sys
>>> pp(sys.path)

There are two environment variables that can modify sys.pathPYTHONHOME sets an alternate value for the prefix of the Python installation. For example, if PYTHONHOME is set to /www/python, the search path will be set to ['', '/www/python/lib/pythonX.Y/', '/www/python/lib/pythonX.Y/plat-linux2', ...].
The PYTHONPATH variable can be set to a list of paths that will be added to the beginning of sys.path. For example, if PYTHONPATH is set to /www/python:/opt/py, the search path will begin with [‘/www/python’, ‘/opt/py’]. (Note that directories must exist in order to be added to sys.path; the site module removes paths that don’t exist.)



运行是通过为os.path添加路径,but 关闭程序后就会失效。

import sys


在linux下就是为 ~/.bashrc 修改 $PATH的内容,比如

export PATH=$PATH:$ORACLE_HOME/bin:/home/jim/source/python/lib/xxx

这是新版本python 2.6开始有的功能,首先确定本平台上site-packages的路径

:~$ python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

例如需要把 /home/azureuser加入path,可以这样做:

~$ sudo gedit /usr/lib/python2.6/dist-packages/a.pth


python 中path的配置方法

[python error] AttributeError:’function’ object has no attribute ‘copy’

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

Interface summary:

Return a shallow copy of x.

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original. copy.deepcopy(x)


import copy
a = [1, 2, 3, 4, [‘a’, ‘b’]] #原始对象
b = a #赋值,传对象的引用
c = copy.copy(a) #对象拷贝,浅拷贝
d = copy.deepcopy(a) #对象拷贝,深拷贝
a.append(5) #修改对象a
a[4].append(‘c’) #修改对象a中的[‘a’, ‘b’]数组对象
print ‘a = ‘, a
print ‘b = ‘, b
print ‘c = ‘, c
print ‘d = ‘, d
a = [1, 2, 3, 4, [‘a’, ‘b’, ‘c’], 5]
b = [1, 2, 3, 4, [‘a’, ‘b’, ‘c’], 5]
c = [1, 2, 3, 4, [‘a’, ‘b’, ‘c’]]
d = [1, 2, 3, 4, [‘a’, ‘b’]]

类和非类对象判断规则Type Or Non-type Test Rule

  • 如果一个对象是<type ‘type’>的实例, 那它就是类对象. 否则是非类对象.
  • .pyc 字节编译的文件,是与平台无关的
    • 直接执行的 py 文件不生成 pyc 文件
    • 直接执行的 py 文件 A 所 import 的 py 文件 B 生成 pyc 文件
    • 再次运行 A 时解释器通过查找与 B 同名的 pyc 文件,通过对比同名 py 文件和 pyc 文件的最后修改时间判断是否需要重新编译 pyc 文件,运行 pyc 文件 [python]

The shelve module implements persistent storage for arbitrary Python objects which can be pickled, using a dictionary-like API. Python的数据持久化操作主要有六类:普通文件、DBM文件、Pickled对象存储、shelve对象存储、对象数据库存储、关系数据库存储。


import shelve, sys

def printshelf (shelf, stream=sys.stdout):  # print the entries in a shelf
    for k in shelf.keys():
        print >>stream, k, '=', shelf[k]

def clearshelf (shelf):                     # remove all keys in the shelf
    for k in shelf.keys():
        del shelf[k]

# create shelf
shelf ="test.shelf")
shelf["x"] = [1,2,3,4]
shelf["y"] = {'a':1, 'b':2, 'c':3}

Open a persistent dictionary.

The filename specified is the base filename for the underlying database. As a side-effect, an extension may be added to the filename and more than one file may be created.

By default, the underlying database file is opened for reading and writing. The optional flag parameter has the same interpretation as the flag parameter of

Value Meaning
'r' Open existing database for reading only (default)
'w' Open existing database for reading and writing
'c' Open database for reading and writing, creating it if it doesn’t exist
'n' Always create a new, empty database, open for reading and writing

idb =‘idbpath’,flag=’r’)


[python error] Indexerror list index out of range

‘list index out of range’ most likely means you are referring to n-th element of the list, while the length of the list is smaller than n.

Using range for iteration is nearly always not the best way. In Python you can iterate directly over a list, dict, set etc.:

for item in d.entries:
    updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": item.title + ", "}])

Obviously d.entries[i] triggers the error because that list contains less than 8 items (feeds_updatesmay contain 8, but you are not iterating over that list).

1) Python’s default behavior for chained comparisons don’t work as you’d expect for numpy arrays.
2) Python doesn’t allow numpy to change this default behavior (at least currently, and maybe never).

Indentationerror unexpected indent

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must start with exactly the same string of whitespace. For instance:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent
“each line within a basic block must be indented by the same amount“. (Wrong use of the term “basic block”, [this python doc]
1) Make sure your lines are indented properly, remembering that Python thinks that tab stops are every 8 columns.
2) Look for a missing colon on the line above, which is usually a forifelsewhiletry, or similar type of line. In general, if a line ends in a colon, the next line with code needs to be indented by some amount.
3)using the -tt‘ command-line option to determine when you accidentally mix tabs and spaces.

sys.argv[1] 【python】

sys.argv is automatically a list of strings representing the arguments (as separated by spaces) on the command-line.

The name comes from the C programming convention in which argv and argc represent the command line arguments.

sys.argv[0] is the name of the script,
sys.argv[1] – sys.argv[n] are the parameters used in the script.


Just another site

Jing's Blog

Just another site

Start from here......







Just another site

Where On Earth Is Waldo?

A Project By Melanie Coles

the Serious Computer Vision Blog

A blog about computer vision and serious stuff

Cauthy's Blog

paper review...

Cornell Computer Vision Seminar Blog

Blog for CS 7670 - Special Topics in Computer Vision


Life through nerd-colored glasses

Luciana Haill

Brainwaves Augmenting Consciousness



Dr Paul Tennent

and the university of nottingham

turn off the lights, please

A bunch of random, thinned and stateless thoughts around the Web

John's Weblog

Just another weblog

I Am That I Am

Chasing tomorrow's sunrise.