Skip to content

Instantly share code, notes, and snippets.

@jyoshida-sci
Last active January 28, 2017 16:40
Show Gist options
  • Save jyoshida-sci/676df0a23bfce94737ae to your computer and use it in GitHub Desktop.
Save jyoshida-sci/676df0a23bfce94737ae to your computer and use it in GitHub Desktop.
Python_OpenCV

#OpenCV Python

##displaying_img.py Displaying all jpg-imgs in a directory in 7 ways; normal,R,G,B,H,S and V-channel

##e07_gridimg_negaimg.py and e373_negaimg.py creating gridimg and negaimg

##sobelmod.py and sobelapp.py module of Sobel-filter and its application

##gabor.py Gabor filter

##flag.py drawing flags

##bmp2dat.py Converting bmp-files into a Kanda's dat file in order of timestamp.

##gridrecog.py and reading xxx-xxx-000.bmp for gridmarks, detecting marks and making a merged image.

##tile.py Creating 0-0.png ~ 3-3.png and making a merged image.

##How to install in a windows-machine ・OpenCVをダウンロード http://opencv.org/ Windows版のあらかじめビルドされた版をダウンロードするのが楽。 実行して出てくるディレクトリ一式を適当な場所に。(例えば C:\opencv\opencv24xx) 自分の環境に合わせてPATHを設定。(例えば C:\opencv\opencv2410\build\x86\vc12\bin)

・Python(x,y)をダウンロード、インストール https://code.google.com/p/pythonxy/ 800MBくらいあるので気長に待つ。 インストーラを実行すると、Pythonの便利なライブラリ(NumpyとかSciPyとか)がインストールされる。 あと、この一式の中に入っているSpyder2というツール(IDE:総合開発環境)がコーディングに便利。

・設定 opencvdir\build\python\2.7\x86 にあるcv2.pydをみつける。 Pythonのディレクトリ C:\Python27\Lib\site-packages をみつける。 ここにcv2.pydをコピー。 サンプルコードを走らせて見て動いたらまずはOK。

"""
Created on Wed Apr 15 10:42:49 2015
指定したディレクトリの中にある全bmpファイルをタイムスタンプ順でunsignedcharのバイナリファイルに書き出す
@author: jyoshida-sci
"""
import cv2
import glob
import os
import struct
#files = glob.glob("\\\\192.168.0.54\\share\\work\\20140509_mod64pl9twin_betaray\\twin_electron\\20140515x100centerbottom\\*.bmp")
files = glob.glob("C:\\imagedir\\*.bmp")
files.sort(key=os.path.getctime)
fout = open('file.dat','wb')
for file in files:
print file
img = cv2.imread(file,cv2.CV_LOAD_IMAGE_GRAYSCALE)
'''enhancing contrast'''
#(minval,maxval,minloc,maxloc) = cv2.minMaxLoc(img)
#minval=20
#maxval=110
#cv2.convertScaleAbs(img, img, 255/(maxval-minval),-255*minval/(maxval-minval))
#print(str.format('{0} {1}', minval,maxval))
for py in range(img.shape[0]):
data = struct.pack('B'*img.shape[1], *img[py])
fout.write(data)
fout.close()
"""
Created on Wed Apr 15 09:27:47 2015
Displaying all jpg-imgs in a directory in 7 ways; normal,R,G,B,H,S and V-channel
画像の表示のサンプル
@author: jyoshida-sci
"""
import cv2
import glob
files = glob.glob("C:\\Users\\Public\\Pictures\\Sample Pictures\\*.jpg")
cv2.namedWindow("display_img",cv2.WINDOW_AUTOSIZE);
cv2.namedWindow("display_img_R",cv2.WINDOW_AUTOSIZE);
cv2.namedWindow("display_img_G",cv2.WINDOW_AUTOSIZE);
cv2.namedWindow("display_img_B",cv2.WINDOW_AUTOSIZE);
cv2.namedWindow("display_img_H",cv2.WINDOW_AUTOSIZE);
cv2.namedWindow("display_img_S",cv2.WINDOW_AUTOSIZE);
cv2.namedWindow("display_img_V",cv2.WINDOW_AUTOSIZE);
for file in files:
print file
img = cv2.imread(file)
RGB =cv2.split(img)
cv2.imshow("display_img",img)
cv2.imshow("display_img_R", RGB[0])
cv2.imshow("display_img_G", RGB[1])
cv2.imshow("display_img_B", RGB[2])
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
HSV = cv2.split(img2)
cv2.imshow("display_img_H", HSV[0])
cv2.imshow("display_img_S", HSV[1])
cv2.imshow("display_img_V", HSV[2])
cv2.waitKey()
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 13:28:01 2015
@author: jyoshida-sci
"""
import cv2
import numpy as np
import sys
def printx(img, m):
#cv2.circle(img, m, 7, 255, 1)
pt1x = m[0] + 5
pt1y = m[1] - 5
pt2x = m[0] - 5
pt2y = m[1] + 5
cv2.line(img, (pt1x, pt1y), (pt2x, pt2y), 0, 2)
pt3x = m[0] - 5
pt3y = m[1] - 5
pt4x = m[0] + 5
pt4y = m[1] + 5
cv2.line(img, (pt3x, pt3y), (pt4x, pt4y), 0, 2)
if __name__ == '__main__':
factor = 3
img = np.ones((350*factor, 345*factor), np.uint8)*255#(height, width)
# cv2.rectangle(img, (0,0), ( 350*factor, 345*factor), 0)
cv2.rectangle(img, (0,0), (345*factor -1, 350*factor -1), 0)#(endx, endy)
distance = 10*factor
offsetX = 3*factor
offsetY = 3*factor
for x in range(35):
for y in range(35):
if x==0:
#cv2.putText(img, "{0}".format(y+1),
cv2.putText(img, "{0}".format(19-(y+1)),
(x*distance + offsetX ,
y*distance+ offsetY +5),
cv2.FONT_HERSHEY_SIMPLEX,
0.4,
0)
if y==0:
#cv2.putText(img, "{0}".format(x+1),
cv2.putText(img, "{0}".format(x+1-18),
(x*distance + offsetX ,
y*distance+ offsetY +5),
cv2.FONT_HERSHEY_SIMPLEX,
0.4,
0)
center = (x*distance + offsetX, y*distance+ offsetY)
cv2.circle(img, center, 1, 0, -1)
xmark = [ (4, 4),(16, 3),(20, 3),(33, 3),
(3,17),(16,17),(20,17),(33,17),
(3,22),(16,21),(20,21),(33,22),
(3,33),(16,33),(20,33),(33,33),
]
for m in xmark:
xx = m[0] - 1
yy = m[1] - 1
markcenter = (xx*distance + offsetX, yy*distance+ offsetY)
printx(img, markcenter)
cv2.line( img,
(17*distance + offsetX, 0*distance+ offsetY),
(17*distance + offsetX, 35*distance+ offsetY),
127,
1)
cv2.line( img,
(0*distance + offsetX, 18*distance+ offsetY),
(35*distance + offsetX, 18*distance+ offsetY),
127,
1)
cv2.imshow('img', img)
cv2.imwrite('07mark.png', img)
nega = cv2.flip(img, 1)#LR-flip
cv2.imwrite('07nega.png', nega)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 13:28:01 2015
@author: jyoshida-sci
"""
import cv2
import numpy as np
import sys
factor = 3
img = np.zeros((245*3,250*3), np.uint8)
for x in range(25):
for y in range(25):
distance = 10*factor
offsetX = 5*factor
offsetY = 3*factor
center = (x*distance + offsetX, y*distance+ offsetY)
cv2.circle(img, center, 1, 255, -1)
for x in range(0,25,12):
for y in range(0,25,12):
distance = 10*factor
offsetX = 5*factor
offsetY = 3*factor
center = (x*distance + offsetX, y*distance+ offsetY)
cv2.circle(img, center, 6, 255, 1)
cv2.imshow('img', img)
cv2.imwrite('373nega.png', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 22 15:19:43 2016
@author: a
"""
import cv2
import numpy as np
def drawStar(img, center, radius, color):
points = []
for i in range(5):
x = radius * np.sin((i*1.0)*np.pi*2.0*3.0/5.0 + np.pi/5.0) + center[0]
y = radius * np.cos((i*1.0)*np.pi*2.0*3.0/5.0 + np.pi/5.0) + center[1]
points.append([x,y])
contours = np.array( points , dtype=np.int32)
cv2.fillPoly(img, [contours], color)
cv2.circle(img, center, int(radius*0.385), (255, 255, 255), -1)
return img
if __name__ == '__main__':
canvas = np.ones((300,450,3), dtype='uint8')*255
#example
testimg = canvas.copy()
cv2.circle(testimg,(100, 100), 10, (0, 0, 255),-1)
cv2.rectangle(testimg, (30, 20), (40, 60), (255, 0, 0),-1)
cv2.line(testimg, (150, 0), (150, 200), (0, 255, 0), 1)
cv2.putText(testimg, "abcdefg", (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 4, 0)
#https://upload.wikimedia.org/wikipedia/commons/9/9e/Flag_of_Japan.svg
#http://www.colorhexa.com/bc002d
japan = canvas.copy()
cv2.circle(japan,(225, 150), 90, (45, 0, 188),-1)
#https://upload.wikimedia.org/wikipedia/commons/9/9e/Flag_of_Japan.svg
france = canvas.copy()
cv2.rectangle(france, (0, 0), (150, 300), (149, 0, 35),-1)
cv2.rectangle(france, (300, 0), (450, 300), (57, 41, 237),-1)
#https://en.wikipedia.org/wiki/Flag_of_Myanmar
myanmar = canvas.copy()
cv2.rectangle(myanmar, (0, 0), (450, 100), (0, 203, 254),-1)
cv2.rectangle(myanmar, (0, 100), (450, 200), (51, 178, 52),-1)
cv2.rectangle(myanmar, (0, 200), (450, 300), (57, 40, 234),-1)
radius = 113
color = (255, 255, 255)
center = (225, 163)
myanmar = drawStar(myanmar, center, radius, color)
#display
cv2.imshow('canvas', canvas)
cv2.imshow('testimg', testimg)
cv2.imshow('japan', japan)
cv2.imshow('france', france)
cv2.imshow('myanmar', myanmar)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28
@author: jyoshida-sci
@input some *.png in the same dir.
"""
import cv2
import glob
import os
import numpy as np
def contrast(img):
(minval,maxval,minloc,maxloc) = cv2.minMaxLoc(img)
if maxval-minval == 0:
return img
enh = np.zeros_like(img)
cv2.convertScaleAbs(img, enh, 255/(maxval-minval),-255*minval/(maxval-minval))
return enh
if __name__ == '__main__':
files = glob.glob("*.png")
files.sort(key=os.path.getmtime)
count = 0
for filename in files:
#print file
img = cv2.imread(filename,cv2.CV_LOAD_IMAGE_GRAYSCALE)
img = contrast(img)
if count == 0:
canvas = img.copy()
else:
np.maximum(canvas, img, canvas)
count += 1
#cv2.imshow('img', img)
#cv2.imshow('canvas', canvas)
#cv2.waitKey(0)
canvas64 = canvas.astype(np.float64)
dstmax = np.zeros(img.shape, np.float64)
for itheta in range(180):
print itheta,
kernel_size = 50
sigma = 1
theta = np.deg2rad(itheta)
lmbda = 2.0
gamma = 0.06
kernelc = cv2.getGaborKernel((kernel_size,kernel_size), sigma, theta, lmbda, gamma, 0);
kernels = cv2.getGaborKernel((kernel_size,kernel_size), sigma, theta, lmbda, gamma, np.deg2rad(-90));
dstc = np.zeros_like(canvas64)
dsts = np.zeros_like(canvas64)
dstc = cv2.filter2D(canvas64, -1, kernelc)
dsts = cv2.filter2D(canvas64, -1, kernels)
#cv.magnitude()
dst = np.zeros_like(canvas64)
dst = cv2.add(dst, cv2.pow(dstc,2))
dst = cv2.add(dst, cv2.pow(dsts,2))
dst = cv2.sqrt(dst)
np.maximum(dst, dstmax, dstmax)
#cv2.imshow('dstc', dstc)
#cv2.imshow('dsts', dsts)
#cv2.imshow('kernelc', kernelc)
#cv2.imshow('kernels', kernels)
#cv2.waitKey(0)
cv2.normalize(dstmax, dstmax, 0, 255, cv2.NORM_MINMAX)
dstmaxdisp = np.zeros(img.shape, np.uint8)
dstdisp = dstmax.astype(np.uint8)
#gaborimg = cv2.pyrDown(dstdisp)
#cv2.imwrite('gaborimg.png', dstdisp)
cv2.imshow('dstdisp', dstdisp)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on Sat May 02 15:29:29 2015
@author: jyoshida-sci
"""
import cv2
import numpy as np
import itertools
#cv2.namedWindow('trim')
markrad = 80
template = np.zeros((markrad*2, markrad*2), np.uint8)
cv2.circle(template, (markrad,markrad), markrad, 1, -1)
grids = np.ones((markrad*2*4, markrad*2*5), np.uint8)*255
rowlist = ([0,1],
[53,54],
[106,107],
[160,161])
collist = (0,9,18,27,36)
img = np.ones((700,2048), np.uint8)*255
f = open('gridmarks.txt', 'w') # 書き込みモードで開く
for c,r in itertools.product(range(len(collist)), range(len(rowlist))):
file0 = "{0:03}-{1:03}-000.bmp".format(collist[c],rowlist[r][0])
aaa = cv2.imread(file0,cv2.CV_LOAD_IMAGE_GRAYSCALE)
img[0:358,0:2048] = aaa
file1 = "{0:03}-{1:03}-000.bmp".format(collist[c],rowlist[r][1])
bbb = cv2.imread(file1,cv2.CV_LOAD_IMAGE_GRAYSCALE)
img[336:336+358,0:2048] = bbb
rev = np.zeros_like(img)
cv2.bitwise_not(img,rev)
res = cv2.matchTemplate(rev,template,eval("cv2.TM_CCORR_NORMED"))
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
#print file
#print max_val
#cv2.circle(img, max_loc, 3, 255, -1)
#bottom_right = (top_left[0] + w, top_left[1] + h)
#cv2.rectangle(img,top_left, bottom_right, (0,0,255), 2)
x = top_left[0]
y = top_left[1]
w, h = template.shape[::-1]
cx = x + w/2
cy = y + h/2
strings = "{0} {1} {2} {3}\n".format(cx, cy, collist[c], rowlist[r][0])
print strings
f.write(strings)
grids[r*h:(r+1)*h, c*w:(c+1)*w] = img[y:y+h,x:x+w].copy()
#trim = img[y:y+h,x:x+w].copy()
#cv2.imshow('trim', trim)
#cv2.waitKey(0)
f.close()
cv2.imwrite('grids.bmp', grids)
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on 20160801
@author: jyoshida-sci
"""
import numpy as np
import sobelmod
if __name__ == '__main__':
myarray = np.random.randint(0,10,(5,6))#0~9random int numbers, 5x6 matrix
sobelx_org, sobely_org, sobelg_org = sobelmod.sobel3_xygrad_org(myarray)
diffx_org, diffy_org, diffg_org = sobelmod.diff3_xygrad_org(myarray)
print myarray
print sobelx_org
print sobely_org
print sobelg_org
print diffx_org
print diffy_org
print diffg_org
# -*- coding: utf-8 -*-
"""
Created on 20160801
@author: jyoshida-sci
"""
import cv2
import numpy as np
def sobel3_xygrad_org(img):
img64 = np.zeros(img.shape, np.float64)
img64 = img.astype(np.float64)
sobel64x = np.zeros(img.shape, np.float64)
sobel64y = np.zeros(img.shape, np.float64)
sobel64g = np.zeros(img.shape, np.float64)
cv2.Sobel(img64, cv2.CV_64F, 1, 0, sobel64x, 3)
cv2.Sobel(img64, cv2.CV_64F, 0, 1, sobel64y, 3)
cv2.magnitude(sobel64x, sobel64y, sobel64g)
return [sobel64x, sobel64y, sobel64g]
def sobel3_xygrad(img):
sobel64x, sobel64y, sobel64g = sobel3_xygrad_org(img)
cv2.normalize(sobel64x, sobel64x, 0, 255, cv2.NORM_MINMAX)
cv2.normalize(sobel64y, sobel64y, 0, 255, cv2.NORM_MINMAX)
cv2.normalize(sobel64g, sobel64g, 0, 255, cv2.NORM_MINMAX)
sobelx_disp = np.zeros(img.shape, np.uint8)
sobelx_disp = sobel64x.astype(np.uint8)
sobely_disp = np.zeros(img.shape, np.uint8)
sobely_disp = sobel64y.astype(np.uint8)
sobelg_disp = np.zeros(img.shape, np.uint8)
sobelg_disp = sobel64g.astype(np.uint8)
return [sobelx_disp, sobely_disp, sobelg_disp]
def diff3_xygrad_org(img):
kdiffx = np.array([[-1.0, 0.0, 1.0],
[-1.0, 0.0, 1.0],
[-1.0, 0.0, 1.0]])
kdiffy = np.array([[-1.0, -1.0, -1.0],
[0.0, 0.0, 0.0],
[1.0, 1.0, 1.0]])
img64 = np.zeros(img.shape, np.float64)
img64 = img.astype(np.float64)
diff64x = cv2.filter2D(img64, -1, kdiffx)
diff64y = cv2.filter2D(img64, -1, kdiffy)
diff64g = np.zeros(img.shape, np.float64)
cv2.magnitude(diff64x, diff64y, diff64g)
return [diff64x, diff64y, diff64g]
def diff3_xygrad(img):
diff64x, diff64y, diff64g = diff3_xygrad_org(img)
cv2.normalize(diff64x, diff64x, 0, 255, cv2.NORM_MINMAX)
cv2.normalize(diff64y, diff64y, 0, 255, cv2.NORM_MINMAX)
cv2.normalize(diff64g, diff64g, 0, 255, cv2.NORM_MINMAX)
diffx_disp = np.zeros(img.shape, np.uint8)
diffx_disp = diff64x.astype(np.uint8)
diffy_disp = np.zeros(img.shape, np.uint8)
diffy_disp = diff64y.astype(np.uint8)
diffg_disp = np.zeros(img.shape, np.uint8)
diffg_disp = diff64g.astype(np.uint8)
return [diffx_disp, diffy_disp, diffg_disp]
if __name__ == '__main__':
myarray = np.random.randint(0,10,(5,6))#0~9random int numbers, 5x6 matrix
sobelx_org, sobely_org, sobelg_org = sobel3_xygrad_org(myarray)
diffx_org, diffy_org, diffg_org = diff3_xygrad_org(myarray)
print myarray
print sobelx_org
print sobely_org
print sobelg_org
print diffx_org
print diffy_org
print diffg_org
################
img = cv2.imread("imgage.png",cv2.CV_LOAD_IMAGE_GRAYSCALE)
sobelx_disp, sobely_disp, sobelg_disp = sobel3_xygrad(img)
diffx_disp, diffy_disp, diffg_disp = diff3_xygrad(img)
cv2.imshow('img', img)
cv2.imshow('sobelx_disp', sobelx_disp)
cv2.imshow('sobely_disp', sobely_disp)
cv2.imshow('sobelg_disp', sobelg_disp)
cv2.imshow('diffx_disp', diffx_disp)
cv2.imshow('diffy_disp', diffy_disp)
cv2.imshow('diffg_disp', diffg_disp)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -*- coding: utf-8 -*-
"""
Created on Fri May 01 19:17:23 2015
@author: jyoshida-sci
"""
import cv2
import numpy as np
import itertools
height = 440
width = 512
#generating images#################
for i, j in itertools.product(range(4), range(4)):
img = np.ones((height,width,1), np.uint8)*255
msg="{0}-{1}".format(i,j)
location=(100,200)
fontface=cv2.FONT_HERSHEY_PLAIN
fontscale=10.0
color=(0,0,0)#black
cv2.putText(img,msg,location,fontface,fontscale,color)
cv2.imwrite("{0}-{1}.png".format(i,j), img)
#joining images####################
bigimg = np.ones((height*4,width*4), np.uint8)*255
for i, j in itertools.product(range(4), range(4)):
sx=i*width
sy=j*height
ex=(i+1)*width
ey=(j+1)*height
filename="{0}-{1}.png".format(i,j)
img = cv2.imread(filename,cv2.IMREAD_GRAYSCALE)
bigimg[sy:ey,sx:ex] = img.copy()
cv2.imwrite("bigimg.png",bigimg)
@jyoshida-sci
Copy link
Author

outputfiles of tile.py
bigimg
1-1

@jyoshida-sci
Copy link
Author

An image for Gabor-filter
fd6fc6d4-4399-11e6-8c62-da2f5dbdb368

@jyoshida-sci
Copy link
Author

outputfiles of e07_gridimg_negaimg.py and e373_negaimg.py
373nega
07nega
07mark

@jyoshida-sci
Copy link
Author

center(0,0)
07nega_c
07mark_c

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