Created
May 21, 2018 06:01
-
-
Save pythonsuezo/cbeb3073f86a7d3ef0a3ca7524f6ef1d to your computer and use it in GitHub Desktop.
カメラ画像加工器その5 カメラ、画像の表示と加工ができるコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, sys | |
import wx | |
import cv2 | |
import cvframe | |
import datetime | |
import configparser | |
import numpy as np | |
from threading import Event, Thread | |
import winsound | |
import re | |
"""---------------------------------------------- | |
カメラ | |
グローバル定数 | |
path : 実行ファイルのディレクトリ | |
today : 今日の日付 | |
now : 今の時間 | |
INI : 設定ファイルの場所 | |
capture : カメラのマウント | |
camera : 起動したときはカメラモードにする | |
設定ファイルに最後に保存したディレクトリの情報を記載する | |
----------------------------------------------""" | |
path = os.path.dirname( sys.argv[0] ) | |
now = datetime.datetime.now() | |
INI = path + "/INI.conf" | |
conf = configparser.SafeConfigParser() | |
capture = cv2.VideoCapture(0) | |
capture.grab() | |
class Mainframe( cvframe.MyFrame1 ): | |
def __init__( self, parent ): | |
cvframe.MyFrame1.__init__( self, parent ) | |
self.nowtime = now.strftime( "%H:%M:%S" ) | |
self.today = now.strftime( "%Y/%m/%d" ) | |
self.camera = True | |
def camera_button( self, event ): | |
self.camera = True | |
def Fileopen( self, event ): | |
"""FileDialog(parent, message=FileSelectorPromptStr, | |
defaultDir="", defaultFile="", | |
wildcard=FileSelectorDefaultWildcardStr, style=FD_DEFAULT_STYLE, | |
pos=DefaultPosition, size=DefaultSize, name=FileDialogNameStr)""" | |
filter = "JPG file(*.jpg)|*.jpg|PNG file(*.png)|*.png|All file(*.*)|*.*" | |
file = wx.FileDialog( None, "ファイルの選択", ".", wildcard = filter, | |
name="画像の選択") | |
result = file.ShowModal() | |
if result == 5101: | |
return | |
self.filename = file.GetPath() | |
print(self.filename) | |
# バイナリから読み込み | |
with open(self.filename, 'rb') as f: | |
binary = f.read() | |
# 一度ndarrayに変換してからdecodeする。日本語ファイルに対応 | |
self.arr = np.asarray(bytearray(binary), dtype=np.uint8) | |
self.camera = False | |
def Grafbutton( self, event ): | |
print("画像を見る") | |
thread = Thread(target = self.Viewloop, name = "loop", args=()) | |
thread.start() | |
def Viewloop(self): | |
negative = False | |
WINDOW_NAME = "frame" | |
self.firstcap = False | |
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL) | |
while not threadevent.wait(0.1): | |
# カメラモードと画像モードはソースを変えるだけ | |
if self.camera: | |
ret, image = capture.read() | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
else: | |
image = cv2.imdecode(self.arr, cv2.IMREAD_UNCHANGED) | |
gray = cv2.imdecode(self.arr, cv2.IMREAD_GRAYSCALE) | |
p1, p2 = self.p1_Val.GetValue(), self.p2_Val.GetValue() | |
effect = self.m_radioBox1.GetSelection() | |
# 効果の選択 | |
if effect == 0: | |
im = image | |
elif effect == 1: | |
im = gray | |
elif effect == 2: | |
im = cv2.Canny(gray, p1, p2) | |
elif effect == 3: | |
ret, im = cv2.threshold(gray, p1, 255, cv2.THRESH_BINARY) | |
else: | |
break | |
# waitKeyの戻り値に0xffをつけることでASCIIコードにする | |
k = cv2.waitKey(10)&0xff | |
# ord(文字)でASCIIコードにする | |
live = cv2.getWindowProperty(WINDOW_NAME, 0) == 0 | |
if k == ord("1"): | |
print("オリジナル") | |
effect = 0 | |
elif k == ord("2"): | |
print("グレー") | |
effect = 1 | |
elif k == ord("3"): | |
print("エッジ") | |
effect = 2 | |
elif k == ord("4"): | |
print("2値化") | |
effect = 3 | |
elif k == ord("n"): | |
if negative: | |
negative = False | |
else: | |
negative =True | |
elif k == ord("s"): | |
self.imagesave(im) | |
elif not live and self.firstcap: | |
print("終わり") | |
threadevent.set() | |
break | |
self.m_radioBox1.SetSelection(effect) | |
if negative: | |
im = cv2.bitwise_not(im) | |
cv2.imshow(WINDOW_NAME, im) | |
self.firstcap = True | |
threadevent.clear() | |
cv2.destroyAllWindows() | |
def imagesave( self, im ): | |
savepath = self.m_dirPicker1.GetPath() # 手動保存のディレクトリ | |
file_name = "pic_" | |
if os.path.exists( savepath ) or savepath == "": | |
savepath = path | |
else: | |
os.mkdir(savepath) | |
save_file = self.New_file(savepath, file_name)[0] | |
cv2.imwrite(save_file, im) | |
winsound.PlaySound('SystemAsterisk', winsound.SND_ASYNC) | |
print(save_file) # パスを表示 | |
return | |
def New_file( self, dir, file_name ): | |
# ディレクトリのパスを受け取って最高値+1のファイル名を返す | |
# 同名ファイルのナンバリング最高値を求める | |
dir_list = os.listdir(dir) # フォルダの中身をリスト化 | |
if len(dir_list) == 0: # ディレクトリ内にファイルがない場合は00000 | |
return dir + "/" + file_name + "00000" + ".jpg", "00000" | |
if [s for s in dir_list if s.startswith(file_name)]: | |
max_num = max([s for s in dir_list if s.startswith(file_name)]).split(".")[0] | |
max_num = re.sub(file_name, r"", max_num) # ファイル名を削除 | |
new_file = "{0:05d}".format(int(max_num)+1) # ファイル名に+1して5ケタでゼロサプレスする | |
else: | |
new_file = "00000" | |
return dir + "/" + file_name + new_file + ".jpg", new_file | |
thread = Thread(target=Mainframe) | |
threadevent = Event() | |
app = wx.App( False ) | |
frame = Mainframe( None ) | |
frame.Show( True ) | |
app.MainLoop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment