Approximating Contour + Convex Hull
import numpy as np
import cv2
import matplotlib.pyplot as plt
def cv2_imshow(title, image):
plt.figure(figsize=(8, 8))
plt.imshow(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
image = cv2.imread('images/house.jpg')
orig_image = image.copy()
cv2_imshow('Original Image', orig_image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
for c in contours:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(orig_image,(x,y),(x+w,y+h),(0,0,255),2)
cv2_imshow('Bounding Rectangle', orig_image)
for c in contours:
accuracy = 0.03 * cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, accuracy, True)
cv2.drawContours(image, [approx], 0, (0, 255, 0), 2)
cv2_imshow('Approx Poly DP', image)
- Convex Hull: 曲線の凸性の欠陥を調べ修正する。手形だと、指の先をつないでくれる。
import numpy as np
import cv2
image = cv2.imread('images/hand.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2_imshow('Original Image', image)
ret, thresh = cv2.threshold(gray, 176, 255, 0)
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
n = len(contours) - 1
contours = sorted(contours, key=cv2.contourArea, reverse=False)[:n]
for c in contours:
hull = cv2.convexHull(c)
cv2.drawContours(image, [hull], 0, (0, 255, 0), 2)
cv2_imshow('Convex Hull', image)
Shape Matching
- matchShapes: 形が近い場合、値が0に近づく
iimport cv2
import numpy as np
import matplotlib.pyplot as plt
def cv2_imshow(title, image):
plt.figure(figsize=(8, 8))
plt.imshow(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
template = cv2.imread('images/4star.jpg',0)
cv2_imshow('Template', template)
target = cv2.imread('images/shapestomatch.jpg')
target_gray = cv2.cvtColor(target,cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(template, 127, 255, 0)
ret, thresh2 = cv2.threshold(target_gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)
template_contour = contours[1]
contours, hierarchy = cv2.findContours(thresh2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
match = cv2.matchShapes(template_contour, c, 3, 0.0)
print(match)
if match < 0.15:
closest_contour = c
else:
closest_contour = []
cv2.drawContours(target, [closest_contour], -1, (0,255,0), 3)
cv2_imshow('Output', target)
Hough Line
import cv2
import numpy as np
import matplotlib.pyplot as plt
def cv2_imshow(title, image):
plt.figure(figsize=(12, 12))
plt.imshow(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
image = cv2.imread('images/soduku.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 170, apertureSize = 3)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 240)
print(lines.shape)
for rho, theta in np.squeeze(lines):
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * (a))
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * (a))
cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
cv2_imshow('Hough Lines', image)
- cv2.HoughLinesP (Probabilistic Hough Lines)
import cv2
import numpy as np
image = cv2.imread('images/soduku.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 170, apertureSize = 3)
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, 5, 10)
print(lines.shape)
for x1, y1, x2, y2 in np.squeeze(lines):
cv2.line(image, (x1, y1), (x2, y2),(0, 255, 0), 3)
cv2_imshow('Probabilistic Hough Lines', image)
- HoughCircles: 円の検出。なかなかうまく行かない
import cv2
import numpy as np
image = cv2.imread('images/bottlecaps.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray, 5)
circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1.43, 10, maxRadius=70)
for i in circles[0,:]:
cv2.circle(image,(i[0], i[1]), i[2], (255, 0, 0), 2)
cv2.circle(image, (i[0], i[1]), 2, (0, 255, 0), 5)
cv2_imshow('detected circles', image)
Blob Detection
import cv2
import numpy as np;
import matplotlib.pyplot as plt
def cv2_imshow(title, image):
plt.figure(figsize=(12, 12))
plt.imshow(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
image = cv2.imread("images/Sunflowers.jpg")
detector = cv2.SimpleBlobDetector_create()
keypoints = detector.detect(image)
blank = np.zeros((1,1))
blobs = cv2.drawKeypoints(image, keypoints, blank, (0,255,255),
cv2.DRAW_MATCHES_FLAGS_DEFAULT)
cv2_imshow("Blobs", blobs)
Counting Circles and Ellipses
- blob は、ぼやっとしていてもはっきりしていても、特定箇所に同じ色が集まっていればOK
import cv2
import numpy as np
import matplotlib.pyplot as plt
def cv2_imshow(title, image):
plt.figure(figsize=(12, 12))
plt.imshow(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
image = cv2.imread("images/blobs.jpg", 0)
cv2_imshow('Original Image',image)
detector = cv2.SimpleBlobDetector_create()
keypoints = detector.detect(image)
blank = np.zeros((1,1))
blobs = cv2.drawKeypoints(image, keypoints, blank, (0,0,255),
cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
number_of_blobs = len(keypoints)
text = "Total Number of Blobs: " + str(len(keypoints))
cv2.putText(blobs, text, (20, 550), cv2.FONT_HERSHEY_SIMPLEX, 1, (100, 0, 255), 2)
cv2_imshow("Blobs using default parameters", blobs)
params = cv2.SimpleBlobDetector_Params()
params.filterByArea = True
params.minArea = 100
params.filterByCircularity = True
params.minCircularity = 0.9
params.filterByConvexity = False
params.minConvexity = 0.2
params.filterByInertia = True
params.minInertiaRatio = 0.01
detector = cv2.SimpleBlobDetector_create(params)
keypoints = detector.detect(image)
blank = np.zeros((1,1))
blobs = cv2.drawKeypoints(image, keypoints, blank, (0,255,0),
cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
number_of_blobs = len(keypoints)
text = "Number of Circular Blobs: " + str(len(keypoints))
cv2.putText(blobs, text, (20, 550), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 100, 255), 2)
cv2_imshow("Filtering Circular Blobs Only", blobs)
www.learnopencv.com