Archive for the Python Category

Note: to fixed “unknown url type: git+https" error for Python setup

Posted in Python with tags , on 2015 年 05 月 13 日 by Kun-Yi

Got an error message on below when run sudo python setup.py to install a new package

Downloading git+https://github.com/Tigge/openant.git#egg=openant-0.2
error: Download error for git+https://github.com/Tigge/openant.git: unknown url type: git+https

just need upgraded setuptools package, use the below command

sudo pip install setuptools –upgrade

Note: histogram equalization by scipy

Posted in Python, scipy with tags on 2014 年 06 月 13 日 by Kun-Yi
click here to see source code 
#!/usr/bin/python
# Source code
import numpy as np
from scipy import misc as mc
import matplotlib.pyplot as plt

def getHist(img):
	h = np.zeros(256)
	for i in img.flatten():
		h[i] = h[i] + 1
	return h

def normalization_histogram(h, t):
	for i in range(256):
		h[i] = h[i]/t
	return h

def getCDF(h):
	cdf = np.zeros(256)
	for i in range(256):
		cdf[i] = sum(h[0:i])
	return cdf

	
lena = mc.lena()
# to get image height & witdh
x, y = lena.shape
# get total pixel
t = x*y

f, axarr = plt.subplots(2,3)
plt.gray()
axarr[0, 0].imshow(lena)
axarr[0, 0].set_title('original image')

hist = getHist(lena)
hist = normalization_histogram(hist, t)
axarr[0, 1].bar(range(256), hist)
axarr[0, 1].set_xlim([0,255])
axarr[0, 1].set_title('historam')

cdp = getCDF(hist)

axarr[0, 2].plot(np.linspace(0,1,256),cdp)
axarr[0, 2].set_title('CDF')

# histogram equalization
nlena = np.zeros([x,y], dtype=np.uint8)
for i in range(x):
	for j in range(y):
		t = cdp[lena[i,j]]*255
		nlena[i,j]=t

axarr[1, 0].imshow(nlena)
axarr[1, 0].set_title('After equlazation')

# re-calc new lena
x, y = nlena.shape
t = x*y
hist = getHist(nlena)
hist = normalization_histogram(hist, t)

axarr[1, 1].bar(range(256), hist)
axarr[1, 1].set_xlim([0,255])
cdf = getCDF(hist)
axarr[1, 2].plot(np.linspace(0,1,256),cdf)

plt.show()

result:

Image

Note: calculate histogram in scipy

Posted in Python, scipy with tags , on 2014 年 06 月 12 日 by Kun-Yi

Note: calculate histogram in scipy

simple calculate histogram

My Rhtymbox RaidoStation file backup

Posted in Linux, Python on 2012 年 06 月 17 日 by Kun-Yi

added Taiwan radio station for Internet into rhythm playlist databass (~/.local/share/rhythmbox\rhythmdb.xml)

https://dl.dropbox.com/u/20887259/rhythmdb.xml

from taiwan.json of Taiwan Radio Tuner v1.4 extact radio station data

 


the python script will merge original database/taiwan.json to stdout

the code ref. http://askubuntu.com/questions/21571/how-to-import-export-radio-station-list-of-rhythmbox & http://docs.python.org/library/json.html

#!/usr/bin/python

import sys
import xml.sax
import json
import pprint
import codecs
from xml.sax import saxutils, handler

#
#
#<rhythmdb version="1.8">
#  <entry type="iradio">
#    <title>WKNC 88.1 FM (NC State) (Low Quality)</title>
#    <genre>Music</genre>
#    <artist></artist>
#    <album></album>
#    <location>http://wknc.sma.ncsu.edu:8000/wkncmq.ogg.m3u</location>
#    <date>0</date>
#    <media-type>application/octet-stream</media-type>
#  </entry>

class RhythmboxPlaylistHandler(handler.ContentHandler):
    def __init__(self, out = sys.stdout):
        self.inRTitle = False
        self.inRLocation = False
	self.inRGenre = False
        self.entrytype = "undefined"
        self.titlebuffer = ""
	self.genrebuffer=""
        self.locationbuffer = ""
	self._out = codecs.getwriter('utf8')(out) # output encoding set to utf-8

    def startElement(self, name, attributes):
        if name == "entry":
            self.entrytype = attributes["type"]  # we're interested in type="iradio"
	    if self.entrytype == "iradio":
		self._out.write('\t<' + name)
		for (name, value) in attributes.items():
            	    self._out.write(' %s="%s"' % (name, saxutils.escape(value)))
		    self._out.write('>\n')
        elif name == "title" and self.entrytype == "iradio":
            self.inRTitle = True
	    self._out.write('\t\t<' + name + '>')
        elif name == "location" and self.entrytype == "iradio":
            self.inRLocation = True
	    self._out.write('\t\t<' + name + '>')
	elif name == "genre" and self.entrytype == "iradio":
            self.inRGenre = True
	    self._out.write('\t\t<' + name + '>')
	elif name == "date" and self.entrytype == "iradio":
	    self._out.write('\t\t<' + name + '>0</' + name + '>\n')
	elif name == "artist" and self.entrytype == "iradio":
	    self._out.write('\t\t<' + name + '>' + '</' + name + '>\n')
	elif name == "album" and self.entrytype == "iradio":
	    self._out.write('\t\t<' + name + '>' + '</' + name + '>\n')
	elif name == "media-type" and self.entrytype == "iradio":
	    self._out.write('\t\t<' + name + '>')
	    self._out.write('application/octet-stream')
	    self._out.write('</' + name + '>\n')
	

    def characters(self, data):
        if self.inRTitle:
            self.titlebuffer += data
	    self._out.write(data)	   
        elif self.inRLocation:
            self.locationbuffer += data
	    self._out.write(data)	   
	elif self.inRGenre:
            self.genrebuffer += data
	    self._out.write(data)	   


    def endElement(self, name):
        if name == "title" and self.inRTitle:
            self.inRTitle = False
	    self._out.write('</' + name + '>\n')
        elif name == "location" and self.inRLocation:
            self.inRLocation = False
	    self._out.write('</' + name + '>\n')
	elif name == "genre" and self.inRGenre:
            self.inRGenre = False
	    self._out.write('</' + name + '>\n')
        elif name == "entry" and self.entrytype == "iradio":
            self.titlebuffer=""
            self.locationbuffer=""
            self.genrebuffer=""
	    self._out.write('\t</' + name + '>\n')


sys.stdout = codecs.getwriter('utf8')(sys.stdout) # output encoding set to utf-8

# create header
sys.stdout.write('<?xml version="1.0" standalone="yes"?>\n')
sys.stdout.write('<rhythmdb version="1.8">\n')

parser = xml.sax.make_parser(  )
handler = RhythmboxPlaylistHandler(  )
parser.setContentHandler(handler)
parser.parse("rhythmdb.xml")

ft=open("taiwan.json", "r")
t = json.load(ft)
for val in t["category"][:]:
	for rs in val["channel"]:
		sys.stdout.write('\t<entry type="iradio">\n')
		sys.stdout.write('\t\t<title>' + rs["title"] + '</title>\n')
		sys.stdout.write('\t\t<genre>' + val["title"] + '</genre>\n')
		sys.stdout.write('\t\t<artist></artist>\n')
		sys.stdout.write('\t\t<album></album>\n')
		sys.stdout.write('\t\t<location>' + rs["url"] + '</location>\n')
		sys.stdout.write('\t\t<date>0</date>\n')
		sys.stdout.write('\t\t<media-type>application/octet-stream</media-type>\n')
		sys.stdout.write('\t</entry>\n')

ft.close()

sys.stdout.write('</rhythmdb>')