Skip to content

Instantly share code, notes, and snippets.

@yuitest
Last active August 29, 2015 14:00
Show Gist options
  • Save yuitest/11299591 to your computer and use it in GitHub Desktop.
Save yuitest/11299591 to your computer and use it in GitHub Desktop.
練習
# coding: utf8
from __future__ import division, print_function, unicode_literals
from collections import namedtuple
class Point(namedtuple('Point', ('x', 'y'))):
__slots__ = ()
class Rect(namedtuple('Rect', ('x', 'y', 'w', 'h'))):
__slots__ = ()
@classmethod
def from_points(cls, (x1, y1), (x2, y2)):
x = min(x1, x2)
y = min(y1, y2)
w = abs(x1 - x2)
h = abs(y1 - y2)
return Rect(x, y, w, h)
@property
def area((x, y, w, h)):
return w * h
def has((x, y, w, h), (px, py)):
if (
x <= px <= x + w and
y <= py <= y + h
):
return True
return False
def vertexes((x, y, w, h)):
return (
Point(x, y),
Point(x + w, y),
Point(x, y + h),
Point(x + w, y + h),
)
def overlap(r1, r2):
points_r1 = tuple(p for p in r1.vertexes() if r2.has(p))
points_r2 = tuple(p for p in r2.vertexes() if r1.has(p))
points = points_r1 + points_r2
if points:
return Rect.from_points(points[0], points[-1])
return None
def similarity(rect1, rect2):
rect3 = rect1.overlap(rect2)
if rect3 is None:
return 0
return rect3.area / (rect1.area * rect2.area) ** .5
@yuitest
Copy link
Author

yuitest commented Apr 25, 2014

ここで書いてる has() のように、 Python の引数を展開する能力やばい。
第一引数(いつもなら self ってかくところ)のところまで出来るのは知らなかった。

@yuitest
Copy link
Author

yuitest commented Apr 25, 2014

ここでの similarity (類似度)は「2 つの長方形がどれくらい重なってるか」を求める意図。
矩形内の 1 ピクセル = 1 要素として見た時のコサイン類似度と等しい(はず)。

@yuitest
Copy link
Author

yuitest commented Apr 25, 2014

overlap の部分は、数学的にはただしい。
しかし、補足がないと、後で「なんだこりゃ」ってなりそう…。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment