import os, glob
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import requests
from scipy import ndimage
from PIL import Image
from io import BytesIO
from IPython.display import Markdown
from IPython.display import Image as DispImage
ds=np.DataSource()
import cv2
class StopExecution(Exception):
def _render_traceback_(self):
pass
def remove_old(name):
if os.path.exists(name):
os.remove(name)
names = ['analysis.html', 'icon-fig.png','plasma_film_Radial.png','plasma_film_Vertical.png']
for name in names:
remove_old(name)
if os.path.exists('Results/'):
file=glob.glob('Results/*')
for f in file:
os.remove(f)
shot_no =0
Vertical=True; Radial=True
if not os.path.exists('Camera_Radial/Data.avi'):
Radial = False
if not os.path.exists('Camera_Vertical/Data.avi'):
Vertical = False
if not Vertical and not Radial: raise StopExecution
"""
FOV=238.08mm (WD=465mm, Sensor height=12.8mm, focal lenght=25mm), resolution=1280x56 => PxLength=238/1280
Need FOV=170mm -> 238-170=68 -> s=68/PxLength-> frames[:,s//2:-s//2]
Edit (17.5.2022)
WD=415 mm
"""
FOV=238
CutFrames=68
PxLength=FOV/1280
s=CutFrames/PxLength
cut=int(s//2)
def get_frame(file, Position='Radial'):
global nFrames
cv2.destroyAllWindows()
video = cv2.VideoCapture(file)
current=0
try:
# os.mkdir('Camera_'+Position)
os.mkdir('Camera_'+Position+'/Frames')
except FileExistsError:
filelist = glob.glob(os.path.join('Camera_'+Position+'/Frames/', "*"))
for f in filelist:
os.remove(f)
while (video.isOpened()):
ret, frame=video.read()
if ret:
name = 'Camera_' + Position + '/Frames/%i.png'%current
if Position == 'Radial':
cv2.imwrite(name, frame[28:-27,cut+150:-cut-150]) #frame[height,width]
else:
cv2.imwrite(name, frame[28:-27,cut+90:-cut-150]) #frame[height,width]
current += 1
else:
break
nFrames=current
video.release()
cv2.destroyAllWindows()
ret, frame=video.read()
return
get_frame('Camera_Radial/Data.avi','Radial')
get_frame('Camera_Vertical/Data.avi','Vertical')
def img_shape(img_name,Position='Radial'):
img=cv2.imread('Camera_'+Position+'/Frames/%s.png'%img_name)
height=img.shape[0]
width=img.shape[1]
return height, width
def make_image(FramStart,FramEnd, Position = 'Radial'):
nFrames=FramEnd-FramStart
frames=[]
width, height = img_shape('0',Position) #width is new height
img_all = np.zeros((height, (FramEnd-FramStart)*width,3), np.uint8)
i=0
for frame in range(FramStart,FramEnd+1):
if Position == 'Radial':
img=cv2.rotate(cv2.imread('Camera_'+Position+f'/Frames/{frame}.png'),cv2.ROTATE_90_CLOCKWISE)
elif Position == 'Vertical':
img=cv2.rotate(cv2.imread('Camera_'+Position+f'/Frames/{frame}.png'),cv2.ROTATE_90_CLOCKWISE)
img_all[:height,i*width:(i+1)*width,:3]=img
i+=1
print('Height:', height, '\nWidth:', width,'\nimg_all shape',img_all.shape)
cv2.imwrite('plasma-film_' + Position + '.png',img_all)
cv2.destroyAllWindows()
def plasma_detect(Position):
plasmaFrame=[]
for frame in range(nFrames):
img=plt.imread('Camera_' + Position + f'/Frames/{frame}.png')
rad=np.sum(img)
if rad>100:
# print(f'Plasma in frame no.{frame}','\nRad=',rad)
plasmaFrame.append(frame)
plasma_start=float(requests.get(f'http://golem.fjfi.cvut.cz/shots/{shot_no}/Diagnostics/PlasmaDetection/Results/t_plasma_start').text)
plasma_end=float(requests.get(f'http://golem.fjfi.cvut.cz/shots/{shot_no}/Diagnostics/PlasmaDetection/Results/t_plasma_end').text)
fStart = int(plasma_start*FPMS);fEnd=int(plasma_end*FPMS)+1
if len(plasmaFrame)==0:
print(f'Plasma detection via camera {Position} failed')
return fStart,fEnd
if abs(fStart-plasmaFrame[0])>2: fStart=plasmaFrame[0]; print('plasma start detection via camera')
if abs(fEnd-plasmaFrame[-1])>2: fEnd=plasmaFrame[-1]; print('plasma end detection via camera')
return fStart, fEnd
def plasma_position(shot_no, plasma_start, plasma_end, Position,fEnd,fStart,symb):
duration = float(plasma_end)-float(plasma_start)
data=np.sum(plt.imread('plasma-film_'+Position+'.png'),axis=2)
width, height = img_shape('0', Position) #width -> height
nFrames=fEnd-fStart
r=[]
for i in range(data.shape[1]):
a=0
b=0
for j in range(data.shape[0]):
a += data[j,i]*j
b += data[j,i]
r_i=(a/b)*(-170/height)
if np.isnan(r_i):
r_i=-85
r.append(r_i+85)
camera_time = np.linspace(float(plasma_start), float(plasma_end), len(r))
plasma_position_data = pd.Series(r, index = camera_time)
return plasma_position_data
FPS = 40000
FPMS = FPS * 1e-3
t_frame = 1 / FPMS #in ms
def PositionAndImg():
if Radial and Vertical: Position = ['Radial', 'Vertical']; nRow = 2
elif Radial: Position = ['Radial']; symb = ['r'];nRow = 1
elif Vertical: Position = ['Vertical'];nRow = 1
fig, ax = plt.subplots(nRow, 1, figsize = (12,6), sharex = True)
if nRow == 1: ax = [ax]
PositionDict = {'Radial': 'r', 'Vertical': 'v'}
for i, (Position, symb) in zip(range(nRow), PositionDict.items()):
fStart, fEnd = plasma_detect(Position)
CamStart = fStart * t_frame; CamEnd = fEnd * t_frame
make_image(fStart, fEnd, Position)
plasma_position_camera = plasma_position(shot_no, CamStart, CamEnd, Position, fEnd, fStart, symb)
FONT = 'DejaVu Sans'
img = Image.open('plasma-film_'+Position+'.png')#.convert('1')
k=8
newsize = (img.size[0]*k, img.size[1])#*3) #resize image
print('newsize',newsize)
img = img.resize(newsize)
cv2.imwrite('plasma-film_' + Position + '2.png',np.asarray(img))
plasma_position_camera.plot(ax = ax[i], label = 'Fast Camera: '+ Position)
ax[i].set_ylabel('$\Delta$'+symb+' [mm]',fontname = FONT, fontweight = 'bold', fontsize = 11)
ax[i].set_ylim(-85,85)
loclegend='best'
leg = ax[i].legend(loc = loclegend, shadow = True, fancybox=False) #with marker
leg.get_frame().set_linewidth(1)
leg.get_frame().set_edgecolor('k')
for text in leg.get_texts():
plt.setp(text, fontname=FONT, fontsize = 8)
for line, text in zip(leg.get_lines(), leg.get_texts()):
text.set_color(line.get_color())
plt.xticks(fontname=FONT, fontweight = 'bold', fontsize = 10)
plt.yticks(fontname=FONT, fontweight = 'bold', fontsize = 10)
ax[i].tick_params(which = 'major', direction='out', length=6, width=1.5)
ax[i].tick_params(which = 'minor', direction='out', length=3, width=1)
ax[i].spines['top'].set_visible(False)
ax[i].spines['right'].set_visible(False)
for axis in ['bottom','left']:
ax[i].spines[axis].set_linewidth(1.5)
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
ax[i].xaxis.set_minor_locator(AutoMinorLocator(2))
ax[i].yaxis.set_minor_locator(AutoMinorLocator(2))
ax[i].grid(which = 'major', c = 'gray', linewidth = 0.5, linestyle = 'solid')
ax[i].grid(which = 'minor', c = 'gray', linewidth = 0.3, linestyle = 'dashed')
# ax[1].set_xlim()
ax[i].axhline(y=0, color='k', ls='--', lw=1, alpha=0.4)
fig.savefig('icon-fig.png')
print(Position)
savedata='Camera_'+Position+'/Camera'+Position+'Position'
plasma_position_camera.to_csv(savedata)
Markdown("[Plasma position camera data](./{})".format(savedata))
ax[-1].set_xlabel('Time [ms]',fontname = FONT, fontweight = 'bold', fontsize = 11)
PositionAndImg()
plasma start detection via camera plasma end detection via camera Height: 616 Width: 1 img_all shape (616, 414, 3) newsize (3312, 616) Radial plasma start detection via camera plasma end detection via camera Height: 676 Width: 1 img_all shape (676, 472, 3) newsize (3776, 676) Vertical
def icon_fig():
vert=plt.imread('plasma-film_Vertical2.png')
rad=plt.imread('plasma-film_Radial2.png')
maxlen=min(vert.shape[1],rad.shape[1])
stacked=np.vstack((rad[:,:maxlen,:],vert[:,:maxlen,:]))
plt.imshow(stacked)
img = cv2.convertScaleAbs(stacked, alpha=(255.0))
font = cv2.FONT_HERSHEY_SIMPLEX; org = [(150, 200),((150, 800))]; fontScale = 4;color = (0, 0,255); thickness = 2
img = cv2.putText(img, 'Radial Position', org[0], font, fontScale, color, thickness, cv2.LINE_AA)
img = cv2.putText(img, 'Vertical Position', org[1], font, fontScale, color, thickness, cv2.LINE_AA)
y_org = [200, 550, 800, 1200]; name = ['LFS','HFS','top', 'bottom']
for n, y in zip(name, y_org):
img = cv2.putText(img, n, (maxlen-600, y), font, fontScale, color, thickness, cv2.LINE_AA)
cv2.imwrite('ScreenShotAll.png',img)
if Vertical and Radial:
icon_fig()
fig, ax = plt.subplots(dpi=200)
im=plt.imread('ScreenShotAll.png')
# ax.axhline(im.shape[0]/4)
# ax.axhline(im.shape[0]*3/4)
plt.imshow(im)
<matplotlib.image.AxesImage at 0x7fd3d1a44fd0>