山内セミナー(2018/12/05)

関連サイトと資料

講義中に試したプログラム

test1.py
import cv2
    
img = cv2.imread('messi5.jpg', cv2.IMREAD_COLOR)
print(img.shape)

bigImg1 = cv2.resize(img, None, fx=2, fy=1.5, interpolation = cv2.INTER_CUBIC)
    
height, width = img.shape[:2]
smallImg1 = cv2.resize(img,(550, 350), interpolation = cv2.INTER_CUBIC)
    
cv2.imshow('original', img)
cv2.imshow('big1', bigImg1)
cv2.imshow('small1', smallImg1)
    
cv2.waitKey(0)
cv2.destroyAllWindows()

test2.py
import cv2
	
bs = 30
img = cv2.imread('messi5.jpg', cv2.IMREAD_COLOR)
	
h, w, _ = img.shape
img2 = cv2.resize(img, None, fx=1/bs, fy=1/bs)    
img3 = cv2.resize(img2, (w, h), interpolation = cv2.INTER_NEAREST)
    
cv2.imshow('original', img)
cv2.imshow('mosaic', img3)
    
cv2.waitKey(0)
cv2.destroyAllWindows()

test3.py
import cv2
	
bs = 10
img = cv2.imread('messi5.jpg', cv2.IMREAD_COLOR)
imgMosaic = img.copy()
imgFace = img[56:(56+77), 197:(197+74)]
	
h, w, _ = imgFace.shape
img2 = cv2.resize(imgFace, None, fx=1/bs, fy=1/bs)    
img3 = cv2.resize(img2, (w, h), interpolation = cv2.INTER_NEAREST)
	
imgMosaic[56:(56+77), 197:(197+74)] = img3
	
cv2.imshow('original', img)
cv2.imshow('Mosaic', imgMosaic)
    
cv2.waitKey(0)
cv2.destroyAllWindows()

test4.py
import cv2
    
img = cv2.imread('gradient.png', cv2.IMREAD_GRAYSCALE)
    
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
    
titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
    
for i in range(len(titles)):
    cv2.imshow(titles[i], images[i])
    
cv2.waitKey(0)
cv2.destroyAllWindows()

test5.py
import cv2
    
img = cv2.imread('dave.jpg', cv2.IMREAD_GRAYSCALE)
#img = cv2.medianBlur(img,5)
    
ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
    
titles = ['Original Image', 'Global Thresholding (v = 127)', 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
    
for i in range(len(titles)):
    cv2.imshow(titles[i], images[i])
    
cv2.waitKey(0)
cv2.destroyAllWindows()

輪郭

cake.jpg

輪郭1.py
# -*- coding: utf-8 -*-
"""
Spyderエディタ

これは一時的なスクリプトファイルです
"""
	
import numpy as np
import cv2
	
im = cv2.imread('cake.jpg', cv2.IMREAD_COLOR)
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
	
ret, thresh = cv2.threshold(imgray, 100, 255, cv2.THRESH_BINARY_INV)
	
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
	
im = cv2.drawContours(im, contours, -1, (0, 255, 0), 3)
cv2.imshow('contours', im)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

輪郭2.py
# -*- coding: utf-8 -*-
"""
Spyderエディタ

これは一時的なスクリプトファイルです
"""
	
import numpy as np
import cv2
	
im = cv2.imread('cake.jpg', cv2.IMREAD_COLOR)
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
	
ret, thresh = cv2.threshold(imgray, 100, 255, cv2.THRESH_BINARY_INV)
	
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
	
im = cv2.drawContours(im, contours, 2, (0, 255, 0), 3)
cv2.imshow('contour', im)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

輪郭3.py
# -*- coding: utf-8 -*-
"""
Spyderエディタ

これは一時的なスクリプトファイルです
"""
	
import numpy as np
import cv2
	
im = cv2.imread('cake.jpg', cv2.IMREAD_COLOR)
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
	
ret, thresh = cv2.threshold(imgray, 100, 255, cv2.THRESH_BINARY_INV)
	
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
	
print(len(contours))
	
cnt = contours[2]
im = cv2.drawContours(im, [cnt], 0, (0, 255, 0), 3)
cv2.imshow('contour', im)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

star.png

輪郭4.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 13:18:06 2017

@author: yama
"""
	
import cv2
	
img = cv2.imread('star.png', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, cv2.THRESH_BINARY)
	
imgEdge, contours, hierarchy = cv2.findContours(thresh, 1, 2)
	
cnt = contours[0]
M = cv2.moments(cnt)
print(M)
	
img = cv2.drawContours(img, [cnt], 0, (0, 255, 0), 3)
cv2.imshow('contour', img)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

輪郭5.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 13:18:06 2017

@author: yama
"""
	
import cv2
	
img = cv2.imread('star.png', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, cv2.THRESH_BINARY)
	
imgEdge, contours, hierarchy = cv2.findContours(thresh, 1, 2)
	
cnt = contours[0]
M = cv2.moments(cnt)
print(M)
	
cx = int(M['m10']/M['m00'])
cy = int(M['m10']/M['m00'])
print('centroid ({0}, {1})'.format(cx, cy))
	
area = cv2.contourArea(cnt)
print('area {0}'.format(area))
	
perimeter = cv2.arcLength(cnt, True)
print('perimeter {0}'.format(perimeter))
	
img = cv2.drawContours(img, [cnt], 0, (0, 255, 0), 3)
cv2.imshow('contour', img)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

flash.png

輪郭6.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 13:18:06 2017

@author: yama
"""
	
import numpy as np
import cv2
	
img = cv2.imread('flash.png', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, cv2.THRESH_BINARY)
	
imgEdge, contours, hierarchy = cv2.findContours(thresh, 1, 2)
	
cnt = contours[0]
x, y, w, h = cv2.boundingRect(cnt)
	
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
	
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
img = cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
cv2.imshow('contour', img)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

輪郭7.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 13:18:06 2017

@author: yama
"""
	
import numpy as np
import cv2
	
img = cv2.imread('flash.png', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, cv2.THRESH_BINARY)
	
imgEdge, contours, hierarchy = cv2.findContours(thresh, 1, 2)
	
cnt = contours[0]
(x,y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
	
img = cv2.circle(img, center, radius, (0, 255, 0), 2)
cv2.imshow('contour', img)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

輪郭8.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 13:18:06 2017

@author: yama
"""
	
import numpy as np
import cv2
	
img = cv2.imread('flash.png', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, cv2.THRESH_BINARY)
	
imgEdge, contours, hierarchy = cv2.findContours(thresh, 1, 2)
	
cnt = contours[0]
ellipse = cv2.fitEllipse(cnt)
	
img = cv2.ellipse(img, ellipse, (0, 255, 0), 2)
cv2.imshow('contour', img)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

輪郭9.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 13:18:06 2017

@author: yama
"""
	
import numpy as np
import cv2
	
img = cv2.imread('flash.png', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, cv2.THRESH_BINARY)
	
imgEdge, contours, hierarchy = cv2.findContours(thresh, 1, 2)
	
h, w = img.shape[:2]
cnt = contours[0]
[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((w - x)*vy/vx)+y)
	
img = cv2.line(img, (w - 1, righty), (0, lefty), (0, 255, 0), 2)
cv2.imshow('contour', img)
cv2.waitKey(0)
	
cv2.destroyAllWindows()

ヒストグラム

home.jpg

ヒストグラム1.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 15:30:59 2017

@author: yama
"""
	
import cv2
import numpy as np
from matplotlib import pyplot as plt
	
img = cv2.imread('home.jpg', cv2.IMREAD_COLOR)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
	
plt.hist(img.ravel(), 256, [0,256]); plt.show()

ヒストグラム2.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 15:30:59 2017

@author: yama
"""
	
import cv2
import numpy as np
from matplotlib import pyplot as plt
	
img = cv2.imread('home.jpg', cv2.IMREAD_COLOR)
color = ('b', 'g', 'r')
for i, col in enumerate(color):
	histr = cv2.calcHist([img], [i], None, [256], [0,256])
	plt.plot(histr, color = col)
	plt.xlim([0,256])
	
plt.show()

ヒストグラム3.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 15:30:59 2017

@author: yama
"""
	
import cv2
import numpy as np
from matplotlib import pyplot as plt
	
img = cv2.imread('home.jpg', cv2.IMREAD_GRAYSCALE)
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv2.bitwise_and(img, img, mask = mask)
	
hist_full = cv2.calcHist([img], [0], None, [256], [0,256])
hist_mask = cv2.calcHist([img], [0], mask, [256], [0,256])
	
plt.subplot(221), plt.imshow(img, 'gray')
plt.subplot(222), plt.imshow(mask, 'gray')
plt.subplot(223), plt.imshow(masked_img, 'gray')
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
plt.xlim([0,256])
	
plt.show()

wiki.jpg

ヒストグラム4.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 23:39:45 2017

@author: yama
"""
	
import cv2
import numpy as np
from matplotlib import pyplot as plt
	
img = cv2.imread('wiki.jpg', cv2.IMREAD_GRAYSCALE)
hist, bins = np.histogram(img.flatten(), 256, [0,256])
	
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max() / cdf.max()
	
plt.plot(cdf_normalized, color = 'b')
plt.hist(img.flatten(), 256, [0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf', 'histogram'), loc = 'upper left')
plt.show()

ヒストグラム5.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 23:39:45 2017

@author: yama
"""
	
import cv2
import numpy as np
from matplotlib import pyplot as plt
	
img = cv2.imread('wiki.jpg', cv2.IMREAD_GRAYSCALE)
hist, bins = np.histogram(img.flatten(), 256, [0,256])
	
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max() / cdf.max()
	
cdf_m = np.ma.masked_equal(cdf, 0)
cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())
cdf = np.ma.filled(cdf_m, 0).astype('uint8')
img2 = cdf[img]
	
hist2, bins2 = np.histogram(img2.flatten(), 256, [0,256])
cdf2 = hist2.cumsum()
cdf2_normalized = cdf2 * hist2.max() / cdf2.max()
	
plt.plot(cdf2_normalized, color = 'b')
plt.hist(img2.flatten(), 256, [0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf', 'histogram'), loc = 'upper left')
plt.show()

ヒストグラム6.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 23:39:45 2017

@author: yama
"""
	
import cv2
import numpy as np
	
img = cv2.imread('wiki.jpg', cv2.IMREAD_GRAYSCALE)
equ = cv2.equalizeHist(img)
res = np.hstack((img, equ))
	
cv2.imshow('result', res)
	
cv2.waitKey(0)
cv2.destroyAllWindows()

ヒストグラム7.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 23:39:45 2017

@author: yama
"""
	
import cv2
import numpy as np
from matplotlib import pyplot as plt
	
img = cv2.imread('home.jpg', cv2.IMREAD_COLOR)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv], [0,1], None, [180, 256], [0, 180, 0, 256])
	
plt.imshow(hist, interpolation = 'nearest')
plt.show()

messi5.jpg

ヒストグラム8.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 18 23:39:45 2017

@author: yama
"""
	
import cv2
import numpy as np
	
img = cv2.imread('messi5.jpg', cv2.IMREAD_COLOR)
roi = img[274:311, 55:162].copy()
hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
	
hsvt = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
	
roihist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
	
cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)
dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)
	
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
cv2.filter2D(dst,-1,disc,dst)
	
ret,thresh = cv2.threshold(dst,50,255,0)
thresh = cv2.merge((thresh,thresh,thresh))
res = cv2.bitwise_and(img,thresh)
	
res = np.vstack((img,thresh,res))
cv2.imshow('result', res)
	
cv2.waitKey(0)
cv2.destroyAllWindows()