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
camera_radial=requests.get(f'http://golem.fjfi.cvut.cz/shots/{shot_no}/Diagnostics/FastCameras/Camera_Radial/data.mp4')
camera_vertical=requests.get(f'http://golem.fjfi.cvut.cz/shots/{shot_no}/Diagnostics/FastCameras/Camera_Vertical/data.mp4')
if camera_vertical.status_code==404: Vertical = False
if camera_radial.status_code==404: Radial = 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)
print('cut',cut)
def get_frame(file, Position='Radial'):
global nFrames
cv2.destroyAllWindows()
video = cv2.VideoCapture(file)
current=0
try:
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.mp4','Radial')
get_frame('Camera_Vertical/data.mp4','Vertical')
cut 182
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/BasicDiagnostics/Results/t_plasma_start').text)
plasma_end=float(requests.get(f'http://golem.fjfi.cvut.cz/shots/{shot_no}/Diagnostics/BasicDiagnostics/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') #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))
camera_position = pd.Series(r, index = camera_time)
return camera_position
def plot(fStart,fEnd,CamStart,CamEnd,Position,symb):
camera_position=plasma_position(shot_no, CamStart, CamEnd,Position,fEnd,fStart,symb)
fig, ax = plt.subplots(2,1,dpi=160)
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))
ax[0].imshow(img)
# ax[0].axhline(880*3/2, color='r',alpha=0.5)
ax[0].set_title(Position + f' plasma position #{shot_no}',fontname = FONT, fontweight = 'bold', fontsize = 15)
ax[0].get_xaxis().set_visible(False)
ax[0].get_yaxis().set_visible(False)
ax[1] = camera_position.plot(label = 'Fast Camera')
ax[1].set_ylabel('$\Delta$'+symb+' [mm]',fontname = FONT, fontweight = 'bold', fontsize = 11)
ax[1].set_xlabel('Time [ms]',fontname = FONT, fontweight = 'bold', fontsize = 11)
ax[1].set_ylim(-85,85)
loclegend='best'
leg = plt.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[1].tick_params(which = 'major', direction='out', length=6, width=1.5)
ax[1].tick_params(which = 'minor', direction='out', length=3, width=1)
ax[0].tick_params(which = 'major', direction='out', length=6, width=1.5)
ax[0].tick_params(which = 'minor', direction='out', length=3, width=1)
ax[1].spines['top'].set_visible(False)
ax[1].spines['right'].set_visible(False)
for axis in ['bottom','left']:
ax[1].spines[axis].set_linewidth(1.5)
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
ax[1].xaxis.set_minor_locator(AutoMinorLocator(2))
ax[1].yaxis.set_minor_locator(AutoMinorLocator(2))
ax[1].grid(which = 'major', c = 'gray', linewidth = 0.5, linestyle = 'solid')
ax[1].grid(which = 'minor', c = 'gray', linewidth = 0.3, linestyle = 'dashed')
# ax[1].set_xlim()
ax[1].axhline(y=0, color='k', ls='--', lw=1, alpha=0.4)
fig.savefig('Plasma_position_Camera')
FPS = 40000
FPMS = FPS*1e-3
t_frame=1/FPMS #in ms
def All(Position='Radial'):
if Position=='Radial':symb='r'
if Position=='Vertical': symb='z'
print('Processing data from Camera '+Position)
fStart,fEnd=plasma_detect(Position)
CamStart=fStart*t_frame; CamEnd=fEnd*t_frame
print('CamStart: {0:.3f},CamEnd {1:.3f}'.format(CamStart,CamEnd))
print('First frame with plasma:',fStart,'\nLast frame with plasma:',fEnd)
make_image(fStart,fEnd, Position)
plot(fStart,fEnd,CamStart,CamEnd,Position,symb)
camera_position=plasma_position(shot_no, CamStart, CamEnd,Position,fEnd,fStart,symb)
savedata='Camera_'+Position+'/Camera'+Position+'Position'
camera_position.to_csv(savedata)
Markdown("[Plasma position camera data](./{})".format(savedata))
if Radial: All('Radial')
Processing data from Camera Radial plasma end detection via camera CamStart: 3.975,CamEnd 15.850 First frame with plasma: 159 Last frame with plasma: 634 Height: 616 Width: 1 img_all shape (616, 475, 3) newsize (3800, 616)
if Vertical: All('Vertical')
Processing data from Camera Vertical plasma start detection via camera plasma end detection via camera CamStart: 4.075,CamEnd 15.725 First frame with plasma: 163 Last frame with plasma: 629 Height: 676 Width: 1 img_all shape (676, 466, 3) newsize (3728, 676)
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('icon-fig.png',img)
if Vertical and Radial:
icon_fig()
fig, ax = plt.subplots(dpi=200)
im=plt.imread('icon-fig.png')
# ax.axhline(im.shape[0]/4)
# ax.axhline(im.shape[0]*3/4)
plt.imshow(im)
<matplotlib.image.AxesImage at 0x7fb506aa8370>