Python-Gphoto2
ナビゲーションに移動
検索に移動
概要
コマンド操作でカメラの制御を行います。 iso感度やシャッタスピード等の設定も可能です.
インストール
- debian
apt install gphoto2
- Python
(My Program)
使用例
カメラのデータ格納やタイミングをスレッドに指示
class data:
def __init__(self):
self.buffer = [b"", b""]
self.e = [False, False]
self.f = False
def set(self, d, val=0):
self.buffer[val] = (b"--frame\r\n"+
b"Content-Type: image/jpeg\r\n\r\n" + d + b"\r\n")
def get(self, val=0):
return self.buffer[val]
def start(self, val=0):
self.e[val] = False
def finish(self, val=0):
self.e[val] = True
def end(self, val=0):
return self.e[val]
def setFinal(self):
self.f = True
def final(self):
return self.f
datas = data()
カメラ設定最適化・初期化
class GPhoto2:
def __init__(self):
self.iso = 3200
self.shutterspeed = 10
self.aperture = 2.8
self.capturetarget = 0
self.autofocusdrive = 0
self.manualfocusdrive = 3
self.eosremoterelease = 0
self.viewfinder = 2
self.autoexposuremode = 3
self.file = ""
self.fileNames = []
self.log = ""
self.json = []
self.setter = {"default":True,"capturetarget":False,"autofocusdrive":False,
"manualfocusdrive":False,"eosremoterelease":False,
"viewfinder":False,"autoexposuremode":False}
self.finish = False
self.turn = 0
self.log2 = "";
self.set();
def default(self):
self.iso = "Auto"
self.shutterspeed = "1/6"
self.aperture = 2.8
self.capturetarget = 0
self.autofocusdrive = 0
self.manualfocusdrive = 3
self.eosremoterelease = 0
self.viewfinder = 2
self.autoexposuremode = 3
def setFileName(self,name):
self.fileNames.append(name)
def getFileName(self):
return self.fileNames
def setting(self):
print("setting")
if self.setter["default"]:
self.log = ""
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'shutterspeed={self.shutterspeed}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'aperture={self.aperture}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'iso={self.iso}'],cwd=r"/home/azuma/public_html/public/" ,stdout=subprocess.PIPE,shell=False).stdout
self.setter["default"] = False
if self.setter["capturetarget"]:
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'capturetarget={self.capturetarget}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.setter["capturetarget"] = False
if self.setter["autofocusdrive"]:
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'autofocusdrive={self.autofocusdrive}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.setter["autofocusdrive"] = False
if self.setter["manualfocusdrive"]:
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'manualfocusdrive={self.manualfocusdrive}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.setter["manualfocusdrive"] = False
if False:
#if self.setter["eosremoterelease"]:
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'eosremoterelease={self.eosremoterelease}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.setter["eosremoterelease"] = False
if self.setter["viewfinder"]:
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'viewfinder={self.viewfinder}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.setter["viewfinder"] = False
if self.setter["autoexposuremode"]:
self.log = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--set-config' ,f'autoexposuremode={self.autoexposuremode}'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout
self.setter["autoexposuremode"] = False
#- 設定
# 各設定や制限などによる代入をコントロールするため個々に設定
def setIso(self,iso):
self.iso = iso
self.setter["default"] = True
def setShutterspeed(self,shutterspeed):
self.shutterspeed = shutterspeed
self.setter["default"] = True
def setAperture(self,aperture):
self.aperture = aperture
self.setter["default"] = True
def setCapturetarget(self,capturetarget):
self.capturetarget = capturetarget
self.setter["capturetarget"] = True
def setAutofocusdrive(self,autofocusdrive):
self.autofocusdrive = autofocusdrive
self.setter["autofocusdrive"] = True
def setManualfocusdrive(self,manualfocusdrive):
self.manualfocusdrive = manualfocusdrive
self.setter["manualfocusdrive"] = True
def setEosremoterelease(self,eosremoterelease):
self.eosremoterelease = eosremoterelease
self.setter["eosremoterelease"] = True
def setViewfinder(self,viewfinder):
self.viewfinder = viewfinder
self.setter["viewfinder"] = True
def setAutoexposuremode(self,autoexposuremode):
self.autoexposuremode = autoexposuremode
self.setter["autoexposuremode"] = True
#gphoto2にあるパラメータを取得
def set(self):
self.json = ["[shutterspeed]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'shutterspeed'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[iso]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'iso'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[aperture]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'aperture'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[capturetarget]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'capturetarget'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[autofocusdrive]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'autofocusdrive'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[manualfocusdrive]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'manualfocusdrive'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[eosremoterelease]\n Sorry... No Parameters",
"\n\n[viewfinder]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'viewfinder'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout),
"\n\n[autoexposuremode]\n"+str(subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--get-config' ,'autoexposuremode'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False).stdout)
]
#- 取得
def get(self):
return self.json
def getIso(self):
return self.iso
def getShutterspeed(self):
return self.shutterspeed
def getAperture(self):
return self.aperture
def getCapturetarget(self):
return self.capturetarget
def getAutofocusdrive(self):
return self.autofocusdrive
def getManualfocusdrive(self):
return self.manualfocusdrive
def getEosremoterelease(self):
return self.eosremoterelease
def getViewfinder(self):
return self.viewfinder
def getAutoexposuremode(self):
return self.autoexposuremode
def AllGet(self):
jsons = [
["Iso",self.getIso()],
["Shutterspeed",self.getShutterspeed()],
["Aperture",self.getAperture()],
["Capturetarget",self.getCapturetarget()],
["Autofocusdrive",self.getAutofocusdrive()],
["Manualfocusdrive",self.getManualfocusdrive()],
["Eosremoterelease",self.getEosremoterelease()],
["Viewfinder",self.getViewfinder()],
["Autoexposuremode",self.getAutoexposuremode()]
]
return jsons
def logs(self):
return self.log
def setFinish(self):
self.finish = True
def getFinish(self):
return self.finish
def filename(self):
if self.file:
if self.turn:
self.file = self.file+"_"+str(self.turn)
path = f"/保存ディレクトリ/{self.file}.jpg"
self.files.append(path)
return f"--filename {path}"
else:
return ""
def getfiles(self):
return self.files
def setTurn(self,turn):
self.turn = turn
def getTurn(self):
return self.turn
def cons(self,msg):
print(str(msg))
self.log2 = str(msg);
def getCons(self):
return self.log2
gphoto = GPhoto2()
カメラ設定最適化・初期化
def video1(threadedname, GPhoto2_datas,d):
savePath = "保存するパス"
print("video1起動")
try:
GPhoto2_datas.setting()
desc = GPhoto2_datas.AllGet()
c = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--force-overwrite','--capture-image-and-download', '--filename', f'{savePath}/capt0000.jpg'],cwd=r"/保存するパス/",shell=False).stdout
GPhoto2_datas.cons(c)
with open(f"/{savePath}/capt0000.jpg",'rb') as f:
img = f.read()
d.set(d=img, val=1)
#時間取得
dt_now = datetime.datetime.now()
month = '{:0=2}'.format(dt_now.month)
day = '{:0=2}'.format(dt_now.day)
hour = '{:0=2}'.format(dt_now.hour)
minute = '{:0=2}'.format(dt_now.minute)
second = '{:0=2}'.format(dt_now.second)
fileName = f"{dt_now.year}{month}{day}{hour}{minute}{second}"
filepath = f"{savePath}/history/Y{dt_now.year}/M{month}/D{day}/{fileName}.jpg"
file_path = os.path.dirname(filepath)
if not os.path.exists(file_path):
os.makedirs(file_path)
try:
with open(filepath,'wb') as wf:
wf.write(img)
GPhoto2_datas.setFileName(fileName)
except:
pass
txt = ""
try:
with open(filepath[:-4]+".txt","w",encoding="utf-8") as tx:
for j in desc:
try:
txt += j[0]+" : "+str(j[1])
except:
txt += "--error--"
txt += "\n"
tx.write(txt)
except:
pass
except:
print("Cameraエラー")
print("video1終了")
撮影・取得(Flask)
@app.route("/schott/systemd/reload",methods=["GET"])
def systemdS():
subprocess.run(['/usr/bin/systemctl',"restart","flask"],stdout=subprocess.PIPE,shell=False)
return "OK"
def formatDate():
dt_now = datetime.datetime.now()
month = '{:0=2}'.format(dt_now.month)
day = '{:0=2}'.format(dt_now.day)
hour = '{:0=2}'.format(dt_now.hour)
minute = '{:0=2}'.format(dt_now.minute)
second = '{:0=2}'.format(dt_now.second)
return f"{dt_now.year}/{month}/{day} {hour}:{minute}:{second}"
@app.route("/schott/reload",methods=["GET"])
def reload():
puts = ["",""]
puts[0] = subprocess.run(['/usr/bin/lsusb'],stdout=subprocess.PIPE,shell=False)
puts[1] = subprocess.run(['/var/lib/snapd/snap/bin/gphoto2', '--auto-detect'],cwd=r"/home/azuma/public_html/public/",stdout=subprocess.PIPE,shell=False)
jsons = {
"EXCETIME":formatDate(),
"lsusb":f'{puts[0].stdout.decode("utf-8")}'.replace("\\n","<br>").replace("\n","<br>"),
"detect":f"{puts[1].stdout.decode('utf-8')}".replace("\\n","<br>").replace("\n","<br>"),
}
return jsonify(jsons)
@app.route("/schott/log",methods=["GET"])
def logsCamera():
lsusb = ""
try:
lsusb = subprocess.run(['/usr/bin/lsusb'],stdout=subprocess.PIPE,shell=False)
#lsusb = subprocess.run(['/usr/bin/lsusb'],shell=False)
except Exception as e:
lsusb = f"エラー発生:{e}"
logsC = gphoto.getCons()
jsons = {
"EXCETIME":formatDate(),
"lsusb":str(lsusb.stdout.decode("utf-8")).replace("\\n","<br>").replace("\n","<br>"),
"log":logsC
}
return jsonify(jsons)
@app.route("/schott/img")
def getFile():
jsons = {
"EXCETIME":formatDate(),
"items":gphoto.getFileName()
}
return jsonify(jsons)
now = formatDate()
@app.route("/schott")
def ref():
global now
dt_now = datetime.datetime.now()
date = now
now = formatDate()
if (maintenance):
return "只今、メンテナンス中です."
return render_template('schott.html',logMessage=maintenance_Message,date=date,year=dt_now.year,month=dt_now.month,day=dt_now.day)
@app.route("/schott/live")
def schLibe():
return Response(gen2(1,5),
mimetype="multipart/x-mixed-replace; boundary=frame")
import pathlib
@app.route("/schott/history",methods=["GET"])
def history():
#imgs = list(pathlib.Path('/home/azuma/public_app/live/').glob("static/ref/history/**/*.jpg",recursive=True))
imgs = list(glob.glob("/home/azuma/public_app/live/static/ref/history/**/*.jpg",recursive=True))
for t in range(len(imgs)):
imgs[t] = str(imgs[t]).strip("/home/azuma/public_app/live/static/ref/history/")
jsons = {
"EXCETIME":formatDate(),
"hit":len(imgs),
"items":imgs
}
return jsonify(jsons)
@app.route("/schott/history/description/<path:path>",methods=["GET"])
def historysDescription(path):
description = ""
try:
with open(f"/home/azuma/public_app/live/static/ref/history/{path}.txt","r",encoding="utf-8") as f:
description = f.read()
except:
description = "txtが生成されていませんでした。"
jsons = {
"EXCETIME":formatDate(),
"items":str(description).replace("\n","<br>")
}
return jsonify(jsons)
@app.route("/schott/sct",methods=["GET"])
def ok():
jsons = {
"EXCETIME":formatDate(),
"status":"0",
"log":""
}
try:
v1 = threading.Thread(target=video1, args=("gphoto", gphoto,datas))
v1.start()
v1.join()
jsons["status"] = "1"
jsons["log"] = "OK!"
except Exception as e:
jsons["status"] = "-1"
jsons["log"] = e
return e
return jsonify(jsons)
@app.route("/schott/get",methods=["GET"])
def schott_get():
jsons = {
"EXCETIME":formatDate(),
"items":gphoto.AllGet()
}
return jsonify(jsons)
#gphoto
@app.route("/schott/set/default",methods=["GET"])
def setDefault():
gphoto.set()
return "RESET!!"
@app.route("/schott/iso/<name>",methods=["GET"])
def iso(name):
try:
gphoto.setIso(name)
except:
jsonify({"iso": "Error", "log": gphoto.logs()}),404
return jsonify({"iso": "OK!"+str(gphoto.getIso()), "log": str(gphoto.logs())})
@app.route("/schott/shutterspeed/",methods=["GET"])
def shutterspeed():
try:
name = request.args.get("shutterspeed")
gphoto.setShutterspeed(name)
except:
jsonify({"shutterspeed": "Error", "log": gphoto.logs()}),404
return jsonify({"shutterspeed": "OK!"+str(gphoto.getShutterspeed()), "log": str(gphoto.logs())})
@app.route("/schott/aperture/<name>",methods=["GET"])
def aperture(name):
try:
gphoto.setAperture(name)
except:
jsonify({"aperture": "Error", "log": gphoto.logs()}), 404
return jsonify({"aperture": "OK!"+str(gphoto.getAperture()), "log": str(gphoto.logs())})
# # # # # #
# self.capturetarget
# self.autofocusdrive
# self.manualfocusdrive
# self.eosremoterelease
# self.viewfinder
# self.autoexposuremode
# # # # # #
@app.route("/schott/capturetarget",methods=["GET"])
def setCapturetarget():
try:
name = request.args.get("capturetarget")
gphoto.setCapturetarget(name)
except:
jsonify({"capturetarget": "Error", "log": gphoto.logs()}), 404
return jsonify({"capturetarget": "OK!"+str(gphoto.getCapturetarget()), "log": str(gphoto.logs())})
@app.route("/schott/autofocusdrive",methods=["GET"])
def setAutofocusdrive():
try:
name = request.args.get("autofocusdrive")
gphoto.setAutofocusdrive(name)
except:
jsonify({"autofocusdrive": "Error", "log": gphoto.logs()}), 404
return jsonify({"autofocusdrive": "OK!"+str(gphoto.getAutofocusdrive()), "log": str(gphoto.logs())})
@app.route("/schott/manualfocusdrive",methods=["GET"])
def setManualfocusdrive():
try:
name = request.args.get("manualfocusdrive")
gphoto.setManualfocusdrive(name)
except:
jsonify({"manualfocusdrive": "Error", "log": gphoto.logs()}), 404
return jsonify({"manualfocusdrive": "OK!"+str(gphoto.getManualfocusdrive()), "log": str(gphoto.logs())})
@app.route("/schott/eosremoterelease",methods=["GET"])
def setEosremoterelease ():
try:
name = request.args.get("eosremoterelease ")
gphoto.setEosremoterelease(name)
except:
jsonify({"eosremoterelease": "Error", "log": gphoto.logs()}), 404
return jsonify({"eosremoterelease": "OK!"+str(gphoto.getEosremoterelease()), "log": str(gphoto.logs())})
@app.route("/schott/viewfinder",methods=["GET"])
def setViewfinder():
try:
name = request.args.get("viewfinder")
gphoto.setViewfinder(name)
except:
jsonify({"viewfinder": "Error", "log": gphoto.logs()}), 404
return jsonify({"viewfinder": "OK!"+str(gphoto.getViewfinder()), "log": str(gphoto.logs())})
@app.route("/schott/autoexposuremode",methods=["GET"])
def setAutoexposuremode():
try:
name = request.args.get("autoexposuremode")
gphoto.setAutoexposuremode(name)
except:
jsonify({"autoexposuremode": "Error", "log": gphoto.logs()}), 404
return jsonify({"autoexposuremode": "OK!"+str(gphoto.getAutoexposuremode()), "log": str(gphoto.logs())})
# # # # # #
# self.capturetarget
# self.autofocusdrive
# self.manualfocusdrive
# self.eosremoterelease
# self.viewfinder
# self.autoexposuremode
# # # # # #
@app.route("/schott/get/aperture/")
def getAperture():
return jsonify({"aperture": gphoto.get()["aperture"]})
@app.route("/schott/get/shutterspeed/")
def getShutterspeed():
return jsonify({"shutterspeed": gphoto.get()["shutterspeed"]})
@app.route("/schott/get/iso/")
def getIso():
return jsonify({"iso": gphoto.get()["iso"]})
@app.route("/schott/get/capturetarget/")
def getCapturetarget():
return jsonify({"capturetarget": gphoto.get()["capturetarget"]})
@app.route("/schott/get/autofocusdrive/")
def getAutofocusdrive():
return jsonify({"autofocusdrive": gphoto.get()["autofocusdrive"]})
@app.route("/schott/get/manualfocusdrive /")
def getManualfocusdrive():
return jsonify({"manualfocusdrive": gphoto.get()["manualfocusdrive"]})
@app.route("/schott/get/eosremoterelease/")
def getEosremoterelease():
return jsonify({"eosremoterelease": gphoto.get()["eosremoterelease"]})
@app.route("/schott/get/viewfinder/")
def getViewfinder():
return jsonify({"viewfinder": gphoto.get()["viewfinder"]})
@app.route("/schott/get/autoexposuremode/")
def getAutoexposuremode():
return jsonify({"autoexposuremode": gphoto.get()["autoexposuremode"]})