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”);

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.

numpy multi-dimensional array




  • ndarray.ndim


  • ndarray.shape


  • ndarray.size


  • ndarray.dtype


  • ndarray.itemsize




NumPy中的数据类型都有几种字符串表示方式,字符串和类型之间的对应关系都储存在typeDict字典中,例如’d’、 ‘double’、’float64’都表示双精度浮点数类型:

>>> np.typeDict["d"]
<type 'numpy.float64'>
>>> np.typeDict["double"]
<type 'numpy.float64'>
>>> np.typeDict["float64"]
<type 'numpy.float64'>


>>> set(np.typeDict.values())
set([<type 'numpy.bool_'>     ,<type 'numpy.int8'>      ,<type 'numpy.int16'>
     <type 'numpy.float32'>   ,<type 'numpy.uint8'>     ,<type 'numpy.complex128'>
     <type 'numpy.unicode_'>  ,<type 'numpy.uint64'>    ,<type 'numpy.int64'>
     <type 'numpy.complex64'> ,<type 'numpy.string_'>   ,<type 'numpy.uint32'>
     <type 'numpy.void'>      ,<type 'numpy.int32'>     ,<type 'numpy.float96'>
     <type 'numpy.object_'>   ,<type 'numpy.uint32'>    ,<type 'numpy.int32'>
     <type 'numpy.float64'>   ,<type 'numpy.complex192'>,<type 'numpy.uint16'> ])


  • arange()类似于内置函数range(),通过指定开始值、终值步长创建表示等差数列的一维数组,注意所得到的结果数组不包含终值。例如下面的程序创建开始值为0、终值为1、步长为0.1的等差数组,注意终值1不在数组中:
>>> np.arange(0,1,0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])
  • linspace()通过指定开始值、终值元素个数创建表示等差数列的一维数组,可以通过endpoint参数指定是否包含终值,缺省值为True,即包含终值。下面两个例子分别演示了endpoint为True和False时的结果,注意endpoint的值会改变数组的等差步长:
    >>> np.linspace(0, 1, 10) # 步长为1/9
    array([ 0.        ,  0.11111111,  0.22222222,  0.33333333,  0.44444444,
            0.55555556,  0.66666667,  0.77777778,  0.88888889,  1.        ])
    >>> np.linspace(0, 1, 10, endpoint=False) # 步长为1/10
    array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])
  • logspace() 建的数组是等比数列。下面的例子产生从10^010^2、有5个元素的等比数列,注意起始值0表示10^0,而终值2表示10^2
  • zeros()、ones()、empty()可以创建指定形状和类型的数组。其中empty()只分配数组所使用的内存,不对数组元素进行初始化操作,因此它的运行速度是最快的。
  • zeros_like()、ones_like()、empty_like()等函数创建和参数数组的形状和类型相同的数组。因此“zeros_like(a)”和“zeros(a.shape, a.dtype)”的效果相同。
  • frombuffer()、fromstring()、fromfile()等函数可以从字节序列或者文件创建数组:
    >>> s = "abcdefgh" #字符串实际上是一个字节序列,每个字符占一个字节
    >>> np.fromstring(s, dtype=np.int8) #从字符串s创建一个8bit的整数数组,该数组正好就是字符串中每个字符的ASCII编码
    array([ 97,  98,  99, 100, 101, 102, 103, 104], dtype=int8)
    >>> np.fromstring(s, dtype=np.int16)#从字符串s创建16bit的整数数组,那么两个相邻的字节就表示一个整数,把字节98和字节97当作一个16位的整数,它的值就是98*256+97 = 25185。可以看出16bit的整数是以低位字节在前(little-endian)的方式保存在内存中的。
    array([25185, 25699, 26213, 26727], dtype=int16)
    >>> 98*256+97


  • 整数作为下标可以获取数组中的某个元素
>>> x = np.arange(10,1,-1)
>>> x
array([10,  9,  8,  7,  6,  5,  4,  3,  2])
>>> x[[3, 3, 1, 8]] # 获取x中的下标为3, 3, 1, 8的4个元素,组成一个新的数组
array([7, 7, 9, 2])
>>> b = x[[3,3,-3,8]]  #下标可以是负数
>>> b[2] = 100
>>> b
array([7, 7, 100, 2])
>>> x   # 由于b和x不共享数据空间,因此x中的值并没有改变
array([10,  9,  8,  7,  6,  5,  4,  3,  2])
>>> x[[3,5,1]] = -1, -2, -3 # 整数序列下标也可以用来修改元素的值
>>> x
array([10, -3,  8, -1,  6, -2,  4,  3,  2])


>>> x[np.array([[3,3,1,8],[3,3,-3,8]])]
array([[7, 7, 9, 2],
       [7, 7, 4, 2]])
>>> x[[3,3,1,8,3,3,-3,8]].reshape(2,4) # 改变数组形状
array([[7, 7, 9, 2],
       [7, 7, 4, 2]])
>>> a = np.arange(0, 60, 10).reshape(-1, 1) + np.arange(0, 6)
>>> a
array([[ 0,  1,  2,  3,  4,  5],
       [10, 11, 12, 13, 14, 15],
       [20, 21, 22, 23, 24, 25],
       [30, 31, 32, 33, 34, 35],
       [40, 41, 42, 43, 44, 45],
       [50, 51, 52, 53, 54, 55]])
  • 通过切片获取的新的数组是原始数组的一个视图。它与原始数组共享同一块数据存储空间:
  • NumPy还提供了整数列表、整数数组布尔数组等几种高级下标存取方法。



试验性的Numpy教程 tutorial

  • ipython是一个净强化的交互Python Shell,对探索NumPy的特性非常方便。
  • matplotlib将允许你绘图
  • Scipy在NumPy的基础上提供了很多科学模块



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