<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>BoxHeadRoom &#187; Python</title>
	<atom:link href="http://boxheadroom.com/tag/python/feed" rel="self" type="application/rss+xml" />
	<link>http://boxheadroom.com</link>
	<description>蝸牛の一歩</description>
	<lastBuildDate>Tue, 07 Feb 2012 13:41:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Pythonで名前つきリスト その2</title>
		<link>http://boxheadroom.com/2011/09/16/namedlist2</link>
		<comments>http://boxheadroom.com/2011/09/16/namedlist2#comments</comments>
		<pubDate>Fri, 16 Sep 2011 06:31:47 +0000</pubDate>
		<dc:creator>boxheadroom</dc:creator>
				<category><![CDATA[PC]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://boxheadroom.com/?p=4843</guid>
		<description><![CDATA[自分用メモ。　ほかの人が読むと目が腐ります。。。

その1を少し改造したもの。手元のスクリプトでよく使うので、blogにも保存。
かなり昔書いたモジュールなので、今　見ると変な書き方も多いかも。
zlibを使って名寄せなどで使っています。
　（今、ほかのマシンでこのモジュールを動かそうとしたらmycollectionsが足りないことに気がついた。）
今からスクリプトを書くのであれば
2.7以降なら OrderedDict
2.6以前なら prdereddictモジュールを使うのが良いと思います。
名前付きリストモジュール。
リストを継承したクラスですが、インデックスとして数値だけでなく名前を使えるように拡張してあります。
使い方は namedtupleっぽい感じで。

#"namedtuple.py"
def namedtuple(tname,tmemberstr):
    __t=tmemberstr.split()
    __a=",".join(__t)

    class _(tuple):

        exec "def __new__(cls, %s):return tuple.__new__(cls,(%s))"%(__a,__a)
        exec "def __init__(self, %s):tuple.__init__(self,(%s))"%(__a,__a)

        def __get__(self,x):

      [...]]]></description>
			<content:encoded><![CDATA[<p>自分用メモ。　ほかの人が読むと目が腐ります。。。<br />
<span id="more-4843"></span><br />
<a href="http://boxheadroom.com/2009/09/30/python_namedlist">その1</a>を少し改造したもの。手元のスクリプトでよく使うので、blogにも保存。<br />
かなり昔書いたモジュールなので、今　見ると変な書き方も多いかも。</p>
<p><a href="http://boxheadroom.com/2009/10/19/py_zlib_cluster">zlibを使って名寄せ</a>などで使っています。<br />
　（今、ほかのマシンでこのモジュールを動かそうとしたらmycollectionsが足りないことに気がついた。）</p>
<p>今からスクリプトを書くのであれば<br />
2.7以降なら <a href="http://www.doughellmann.com/PyMOTW-ja/collections/ordereddict.html">OrderedDict</a><br />
2.6以前なら <a href="http://pypi.python.org/pypi/ordereddict/">prdereddict</a>モジュールを使うのが良いと思います。</p>
<p>名前付きリストモジュール。<br />
リストを継承したクラスですが、インデックスとして数値だけでなく名前を使えるように拡張してあります。<br />
使い方は <a href="http://www.python.jp/doc/2.6/library/collections.html#collections.namedtuple">namedtuple</a>っぽい感じで。</p>
<pre class="code">
#"namedtuple.py"
def namedtuple(tname,tmemberstr):
    __t=tmemberstr.split()
    __a=",".join(__t)

    class _(tuple):

        exec "def __new__(cls, %s):return tuple.__new__(cls,(%s))"%(__a,__a)
        exec "def __init__(self, %s):tuple.__init__(self,(%s))"%(__a,__a)

        def __get__(self,x):

            return self[__t.index(x)]

    for m in __t :
        setattr(_,m,property(lambda self,p=m:self.__get__(p)))        

    _.__name__=tname

    return _

def namedlist(lname,lmemberstr):
    __m=lmemberstr.split()
    __ka="=0,".join(__m)+"=0"
    __a=",".join(__m)

    __idx=dict(zip(__m,range(len(__m))))
    __sep=[":",]*len(__m)
    class _(list):

        exec "def __new__(cls, %s):return list.__new__(cls,[%s])"%(__ka,__a)
        exec "def __init__(self, %s):list.__init__(self,[%s])"%(__ka,__a)

        def __get__(self,x):
            return self[__idx[x]]
        @classmethod
        def getp(cls,x,p):

            return x[cls.__idx[p]]
        @classmethod
        def indexp(cls,p):
            return cls.__idx[p]

        def __set__(self,x,v):
            self[__idx[x]]=v

    for m in __m :
        setattr(_,m,property(lambda self,p=m:self.__get__(p),
                             lambda self,v,p=m:self.__set__(p,v)))
    _.__member=__m
    _.__idx=__idx
    _.__name__=lname

    return _

#################
# ここから下はテスト的な何か
# 未だに　ちゃんとしたテストの書き方がよくわかりません。
#################

if __name__=="__main__":
    """
    X=namedlist("X","a b c")
    x=X(1,2,3)
    print "x",x
    print "x.a",x.a
    print "x.b",x.b
    print "x.c",x.c
    print "x[0]",x[0]
    print "x[:]",x[:]
    x.a=100
    x.b*=100
    x[-1]=300
    print x
    """
    Pos3d=namedlist("Pos3d","x y z")
    p=Pos3d()
    print p
    X=namedlist("X","a b c")
    x=X(1,2,3)
    print "x",x
    print "x.a",x.a
    print "x.b",x.b
    print "x.c",x.c
    print "x[0]",x[0]
    print "x[:]",x[:]
    x.a=100
    x.b*=100
    x[-1]=300
    print "x",x
    print "list(x)",list(x)
    print "x[:]=[1,2,3][:]"
    x[:]=[1,2,3][:]
    print "x",x
    print "x.a x.b x.c",x.a,x.b,x.c
    print "x.indexp('a'),x.indexp('b'),x.indexp('c')"
    print x.indexp('a'),x.indexp('b'),x.indexp('c')
</pre>
<p>こういうスニペットを保存するにはgithubなどを使うほうがよいのかもしれませんけれども。</p>

	Tags: <a href="http://boxheadroom.com/tag/python" title="Python" rel="tag">Python</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://boxheadroom.com/2011/02/11/urllib2_range" title="【Py】webページの先頭数バイトだけ取得 (2月 11, 2011)">【Py】webページの先頭数バイトだけ取得</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/10/29/wget_py" title="wget.py webをまとめて取得　などなど (10月 29, 2010)">wget.py webをまとめて取得　などなど</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/21/py_cui_progress_ba" title="CUIでプログレスバーもどき (9月 21, 2010)">CUIでプログレスバーもどき</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/18/matplotlib_delaunay" title="ドロネー三角形 matplotlibで (9月 18, 2010)">ドロネー三角形 matplotlibで</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/07/cv_py_delaunay" title="OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー） (9月 7, 2010)">OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー）</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://boxheadroom.com/2011/09/16/namedlist2/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>【Py】webページの先頭数バイトだけ取得</title>
		<link>http://boxheadroom.com/2011/02/11/urllib2_range</link>
		<comments>http://boxheadroom.com/2011/02/11/urllib2_range#comments</comments>
		<pubDate>Thu, 10 Feb 2011 16:42:10 +0000</pubDate>
		<dc:creator>boxheadroom</dc:creator>
				<category><![CDATA[PC]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://boxheadroom.com/?p=4382</guid>
		<description><![CDATA[各種データ収集の際、webページやデータファイルの先頭数バイトだけ欲しいときがたまに有ります。
そんな時には、Rangeヘッダを使うらしいです。
 HTTP入門
以下　コード例

スクリプトを書いて　調べてみました。

opener = urllib2.build_opener()
opener.addheaders = [
    #これはお好みで
    #("User-agent",
    #   "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"), 

    　#今回のキモ
    ("Range","bytes=0-1023"), 

    ]
uri="http://～～～取得したいページ～～～～"
op=opener.open(uri,timeout=30)
dat=op.read(1024)

for i in op.headers.headers :
    print i

op.close()
～～　あとはdatを好きにに料理～～

ネットワークの状態を表示させて受信データの量を調べてみると、
・Rangeヘッダ不使用だと(大きなファイルでも)　20kバイト
・Rangeヘッダを使った場合、およそ2kバイト
なので、データの転送量が10分の1に減ってるみたいです。
大きなファイルの場合、いきなり全部のデータが送られてくるわけではないのですが、転送量の最小サイズは送られてきてしまうので、Rangeヘッダで指定したほうが、若干、転送量が減る、みたいです。
ファイルを1000個ぐらいダウンロードすると若干サーバへの負荷が違ってくる、かも。
あと、今回調べたのはJPEG画像ファイルなど静的ファイルについて。
CGIやPHPなどの、動的コンテンツでは効果無い、かもです。（たぶん）

	Tags: Python

	Related posts
	
	Pythonで名前つきリスト その2 (0)
	wget.py [...]]]></description>
			<content:encoded><![CDATA[<p>各種データ収集の際、webページやデータファイルの先頭数バイトだけ欲しいときがたまに有ります。</p>
<p>そんな時には、Rangeヘッダを使うらしいです。<br />
<a href="http://www.tohoho-web.com/ex/http.htm"> HTTP入門</a></p>
<p>以下　コード例</p>
<p><span id="more-4382"></span><br />
スクリプトを書いて　調べてみました。</p>
<pre class="code">
opener = urllib2.build_opener()
opener.addheaders = [
    #これはお好みで
    #("User-agent",
    #   "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"), 

    　#今回のキモ
    ("Range","bytes=0-1023"), 

    ]
uri="http://～～～取得したいページ～～～～"
op=opener.open(uri,timeout=30)
dat=op.read(1024)

for i in op.headers.headers :
    print i

op.close()
～～　あとはdatを好きにに料理～～
</pre>
<p>ネットワークの状態を表示させて受信データの量を調べてみると、<br />
・Rangeヘッダ不使用だと(大きなファイルでも)　20kバイト<br />
・Rangeヘッダを使った場合、およそ2kバイト</p>
<p>なので、データの転送量が10分の1に減ってるみたいです。</p>
<p>大きなファイルの場合、いきなり全部のデータが送られてくるわけではないのですが、転送量の最小サイズは送られてきてしまうので、Rangeヘッダで指定したほうが、若干、転送量が減る、みたいです。</p>
<p>ファイルを1000個ぐらいダウンロードすると若干サーバへの負荷が違ってくる、かも。</p>
<p>あと、今回調べたのはJPEG画像ファイルなど静的ファイルについて。<br />
CGIやPHPなどの、動的コンテンツでは効果無い、かもです。（たぶん）</p>

	Tags: <a href="http://boxheadroom.com/tag/python" title="Python" rel="tag">Python</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://boxheadroom.com/2011/09/16/namedlist2" title="Pythonで名前つきリスト その2 (9月 16, 2011)">Pythonで名前つきリスト その2</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/10/29/wget_py" title="wget.py webをまとめて取得　などなど (10月 29, 2010)">wget.py webをまとめて取得　などなど</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/21/py_cui_progress_ba" title="CUIでプログレスバーもどき (9月 21, 2010)">CUIでプログレスバーもどき</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/18/matplotlib_delaunay" title="ドロネー三角形 matplotlibで (9月 18, 2010)">ドロネー三角形 matplotlibで</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/07/cv_py_delaunay" title="OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー） (9月 7, 2010)">OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー）</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://boxheadroom.com/2011/02/11/urllib2_range/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>wget.py webをまとめて取得　などなど</title>
		<link>http://boxheadroom.com/2010/10/29/wget_py</link>
		<comments>http://boxheadroom.com/2010/10/29/wget_py#comments</comments>
		<pubDate>Fri, 29 Oct 2010 09:55:28 +0000</pubDate>
		<dc:creator>boxheadroom</dc:creator>
				<category><![CDATA[PC]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://boxheadroom.com/?p=4319</guid>
		<description><![CDATA[linuxのwgetコマンドぽいものをPythonで。
svnからソースをまとめてもらってきたいけどsvnがインスコしてないときなどに使います。
（普段のWebの保存にはfirefoxのscrapbook拡張を使ってます）
Vista+Python2.5, 2.6で動作確認

久しぶりに使おうと思ったら、見つけるのに時間がかかったのでblogにもメモ。
wget.pyとして保存

#Reuse as free as public domain.
import urllib2
import xml.etree.ElementTree as etree
from BeautifulSoup import BeautifulSoup
import os
import re

def wget(url,maxdepth=0,depth=0):
    global op,html,u
    print url
    if depth&#62;maxdepth: return
    op=urllib2.build_opener().open(url)
    html=op.read()
    p,b=mkdir(url)
    print p,"@",b
    if b [...]]]></description>
			<content:encoded><![CDATA[<p>linuxのwgetコマンドぽいものをPythonで。<br />
svnからソースをまとめてもらってきたいけどsvnがインスコしてないときなどに使います。<br />
（普段のWebの保存にはfirefoxのscrapbook拡張を使ってます）</p>
<p>Vista+Python2.5, 2.6で動作確認</p>
<p><span id="more-4319"></span><br />
久しぶりに使おうと思ったら、見つけるのに時間がかかったのでblogにもメモ。</p>
<p>wget.pyとして保存</p>
<pre class="code">
#Reuse as free as public domain.
import urllib2
import xml.etree.ElementTree as etree
from BeautifulSoup import BeautifulSoup
import os
import re

def wget(url,maxdepth=0,depth=0):
    global op,html,u
    print url
    if depth&gt;maxdepth: return
    op=urllib2.build_opener().open(url)
    html=op.read()
    p,b=mkdir(url)
    print p,"@",b
    if b :

        open("%s/%s"%(p,quote(b)),"wb").write(html)
    else :

        open("%s/%s"%(p,"index.html"),"wb").write(html)
        if depth&gt;=maxdepth:return
        soup=BeautifulSoup(html)
        if not soup : return
        for i in soup.findAll("a"):
            href=i["href"]
            if re.match("https?://",href) :
                continue

            u=urllib2.urlparse.urljoin(url, href)
            if u.endswith("/") and u.startswith(url):
                wget(u,depth+1)
            else :
                dl(u)

def dl(url):
    p,b=mkdir(url)
    if not b :
        return
    fn="%s/%s"%(p,b)
    if os.path.exists(fn):
        return
    op=urllib2.build_opener()
    html=op.open(url).read()
    fp=open(fn,"wb")
    fp.write(html)
    fp.close()

def quote(txt):
    if txt.startswith("?"): txt=txt[1:]
    if txt.startswith("."):txt="_"+txt
    txt=urllib2.quote(txt,safe="")

    for rep in """\/:*?"&lt;&gt;|""":
        txt=txt.replace(rep,"%"+hex(ord(rep)))
    return txt
def mkdir(fullurl):
    dl_dir =fullurl[:]
    if dl_dir.lower().startswith("http://") :
        dl_dir=dl_dir[7:]
    dlist=dl_dir.split("/")
    dd="."
    for j  in dlist[:-1]:

        if not j : continue
        dd="%s/%s"%(dd,quote(j))
        #print dd
        if not os.path.exists(dd):
            os.mkdir(dd)

    print dd
    return dd,quote(dlist[-1])

if __name__=="__main__":

    urls=[
#取得したいurl一覧
#例　svnをhttp越しに取得するとき
#url="http://pyglet.googlecode.com/svn/trunk/",　#pyglet
"http://away3d.googlecode.com/svn/trunk/fp10/Away3DLite/"
#away3dlight.lights.Light.as　などが欲しかった
    ]
    for u in urls:
        wget(u,maxdepth=2)
</pre>

	Tags: <a href="http://boxheadroom.com/tag/python" title="Python" rel="tag">Python</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://boxheadroom.com/2011/09/16/namedlist2" title="Pythonで名前つきリスト その2 (9月 16, 2011)">Pythonで名前つきリスト その2</a> (0)</li>
	<li><a href="http://boxheadroom.com/2011/02/11/urllib2_range" title="【Py】webページの先頭数バイトだけ取得 (2月 11, 2011)">【Py】webページの先頭数バイトだけ取得</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/21/py_cui_progress_ba" title="CUIでプログレスバーもどき (9月 21, 2010)">CUIでプログレスバーもどき</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/18/matplotlib_delaunay" title="ドロネー三角形 matplotlibで (9月 18, 2010)">ドロネー三角形 matplotlibで</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/07/cv_py_delaunay" title="OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー） (9月 7, 2010)">OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー）</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://boxheadroom.com/2010/10/29/wget_py/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CUIでプログレスバーもどき</title>
		<link>http://boxheadroom.com/2010/09/21/py_cui_progress_ba</link>
		<comments>http://boxheadroom.com/2010/09/21/py_cui_progress_ba#comments</comments>
		<pubDate>Mon, 20 Sep 2010 17:48:30 +0000</pubDate>
		<dc:creator>boxheadroom</dc:creator>
				<category><![CDATA[PC]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://boxheadroom.com/?p=4268</guid>
		<description><![CDATA[個人的にはIDLE上で短いPythonスクリプトを動かすことが多いのですが、vistaでちょっと大きめのプログラムを動かすと　「（反応なし）」って表示されちゃうこと、ありがち、ですよね？
というわけで、コマンドライン用のプログレスバーもどきを作ってみました。


# -*- coding: utf8 -*-
# pbar.py
#lisence : as same as Python it self

from __future__ import print_function
class PBar(object):
    "progress bar for CUI"
    def __init__(self,n,title=""):
        self.n=n
        self.title=title
        self.ntic=n//20
   [...]]]></description>
			<content:encoded><![CDATA[<p>個人的にはIDLE上で短いPythonスクリプトを動かすことが多いのですが、vistaでちょっと大きめのプログラムを動かすと　「（反応なし）」って表示されちゃうこと、ありがち、ですよね？<br />
というわけで、コマンドライン用のプログレスバーもどきを作ってみました。<br />
<span id="more-4268"></span></p>
<pre class="code">
# -*- coding: utf8 -*-
# pbar.py
#lisence : as same as Python it self

from __future__ import print_function
class PBar(object):
    "progress bar for CUI"
    def __init__(self,n,title=""):
        self.n=n
        self.title=title
        self.ntic=n//20
        self.counter=0
    def tic(self):
        "call once per loop"
        c=self.counter
        if c==0:
            print ()
            print (self.title)
            print ("- - - - + "*4)
        if not c % self.ntic:
            #print ".",
            print (". ",end="")
        if c&gt;=self.n-1:
            print ()
        self.counter+=1

if __name__=="__main__":
    import time
    #class
    bar=PBar(100,"Hello World. Please wait...")

    for i in range(100):
        time.sleep(0.01)
        bar.tic()
    print ("done")
</pre>
<p>テスト実行結果</p>
<blockquote><p><TT><br />
please wait&#8230;<br />
- &#8211; - &#8211; + &#8211; - &#8211; - + &#8211; - &#8211; - + &#8211; - &#8211; - +<br />
. . . . . . . . . . . . . . . . . . . .<br />
done<br />
</TT></p></blockquote>
<p><s>水木さんのマンガのように</s>点々が増えていきます。<br />
ジェネレーター版はこちら</p>
<p><a href="http://code.activestate.com/recipes/576986-progress-bar-for-console-programs-as-iterator/">Recipe 576986: Progress Bar for Console Programs as Iterator (Python) </a></p>

	Tags: <a href="http://boxheadroom.com/tag/python" title="Python" rel="tag">Python</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://boxheadroom.com/2011/09/16/namedlist2" title="Pythonで名前つきリスト その2 (9月 16, 2011)">Pythonで名前つきリスト その2</a> (0)</li>
	<li><a href="http://boxheadroom.com/2011/02/11/urllib2_range" title="【Py】webページの先頭数バイトだけ取得 (2月 11, 2011)">【Py】webページの先頭数バイトだけ取得</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/10/29/wget_py" title="wget.py webをまとめて取得　などなど (10月 29, 2010)">wget.py webをまとめて取得　などなど</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/18/matplotlib_delaunay" title="ドロネー三角形 matplotlibで (9月 18, 2010)">ドロネー三角形 matplotlibで</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/07/cv_py_delaunay" title="OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー） (9月 7, 2010)">OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー）</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://boxheadroom.com/2010/09/21/py_cui_progress_ba/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ドロネー三角形 matplotlibで</title>
		<link>http://boxheadroom.com/2010/09/18/matplotlib_delaunay</link>
		<comments>http://boxheadroom.com/2010/09/18/matplotlib_delaunay#comments</comments>
		<pubDate>Fri, 17 Sep 2010 18:28:51 +0000</pubDate>
		<dc:creator>boxheadroom</dc:creator>
				<category><![CDATA[CG]]></category>
		<category><![CDATA[PC]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://boxheadroom.com/?p=4259</guid>
		<description><![CDATA[いままで気がつかなかったのですが、matplotlibにも、ドロネー三角形を作成するモジュールがありました。使い方メモ。


# -*- coding: utf8 -*-
"""example for matplotlib.delaunay.triangulate
ドロネー三角形サンプルコード"""

import matplotlib.pyplot as plt
from matplotlib.delaunay.triangulate import Triangulation
import numpy as np

#matplotlib 初期化
plt.interactive(True)
fig=plt.figure(111)
fig.clear()
ax = fig.add_subplot(111)

#ランダムな点を作成
x=np.random.randn(100) # X 座標
y=np.random.randn(100) # Y 座標

#点からドロネー三角形を作成
tri=Triangulation(x,y) #　

plt.plot(x,y,"ro") #赤で点を表示

#エッジの連結順序を取り出し
for edge  in tri.edge_db:
    i , j = edge
    # i 番目の点と j 番目の点を連結する線を引く
    plt.plot( [x[i],x[j]], [y[i],y[j]] ,"b") #青で線を引く
 [...]]]></description>
			<content:encoded><![CDATA[<p>いままで気がつかなかったのですが、matplotlibにも、ドロネー三角形を作成するモジュールがありました。使い方メモ。<br />
<span id="more-4259"></span></p>
<pre class="code">
# -*- coding: utf8 -*-
"""example for matplotlib.delaunay.triangulate
ドロネー三角形サンプルコード"""

import matplotlib.pyplot as plt
from matplotlib.delaunay.triangulate import Triangulation
import numpy as np

#matplotlib 初期化
plt.interactive(True)
fig=plt.figure(111)
fig.clear()
ax = fig.add_subplot(111)

#ランダムな点を作成
x=np.random.randn(100) # X 座標
y=np.random.randn(100) # Y 座標

#点からドロネー三角形を作成
tri=Triangulation(x,y) #　

plt.plot(x,y,"ro") #赤で点を表示

#エッジの連結順序を取り出し
for edge  in tri.edge_db:
    i , j = edge
    # i 番目の点と j 番目の点を連結する線を引く
    plt.plot( [x[i],x[j]], [y[i],y[j]] ,"b") #青で線を引く
    #
    #plt.plot( x[edge], y[edge], "b" ) #ホントは、こう書いたほうが速い

plt.show() # IDLEから起動するときはコメントアウト
</pre>
<p>サンプルコードでは画面表示を伴ってるので点100個ぐらいでもちょっと重いですが、点を与えてドロネー三角形に分割するだけなら　千個ぐらいの点でも一瞬です。</p>
<p>こっちのほうがOpenCVを使うよりも断然　お手軽ですね。もっと早く知りたかったですｗ  連結順序だけでなく、個々の三角形として取り出す方法もあるようです。</p>
<p>これは、主として、matplotlib.mlab.griddata関数から使うために用意されているようです。</p>
<p><a href="http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.griddata">matplotlib.mlab.griddata(x, y, z, xi, yi, interp=&#8217;nn&#8217;)</a></p>
<p><a href="http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data">Cookbook / Matplotlib / Gridding irregularly spaced data </a></p>

	Tags: <a href="http://boxheadroom.com/tag/cg" title="CG" rel="tag">CG</a>, <a href="http://boxheadroom.com/tag/math" title="Math" rel="tag">Math</a>, <a href="http://boxheadroom.com/tag/python" title="Python" rel="tag">Python</a><br />

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://boxheadroom.com/2011/09/16/namedlist2" title="Pythonで名前つきリスト その2 (9月 16, 2011)">Pythonで名前つきリスト その2</a> (0)</li>
	<li><a href="http://boxheadroom.com/2011/02/11/urllib2_range" title="【Py】webページの先頭数バイトだけ取得 (2月 11, 2011)">【Py】webページの先頭数バイトだけ取得</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/10/29/wget_py" title="wget.py webをまとめて取得　などなど (10月 29, 2010)">wget.py webをまとめて取得　などなど</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/21/py_cui_progress_ba" title="CUIでプログレスバーもどき (9月 21, 2010)">CUIでプログレスバーもどき</a> (0)</li>
	<li><a href="http://boxheadroom.com/2010/09/07/cv_py_delaunay" title="OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー） (9月 7, 2010)">OpenCV + Pythonで ドロネー△　（どろねーさん、かっけー）</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://boxheadroom.com/2010/09/18/matplotlib_delaunay/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

