Creating flv from image in Matlab - image

I'm trying to make flv file from images via the following Matlab code.The problem is converting bmp images fo flv.
I'm almost new in this section of Matlab. do you have any Idea?
clear
clc
vidobj = videoinput('winvideo',2);
preview(vidobj);
No_snapshot = 5;
interval = 1;
Format = 'bmp';
PathName = uigetdir;
tic;
count = 0;
date_temp = datevec(now);
date_string_vid = [num2str(date_temp(1)),'-',num2str(date_temp(2)),'-',num2str(date_temp(3)),'-',...
num2str(date_temp(4)),'-',num2str(date_temp(5)),'-',num2str(date_temp(6))];
while 1
if fix(toc/interval) > count
count = fix(toc/interval);
date_string = num2str(count);
imwrite(getsnapshot(vidobj),[PathName,'\',date_string,'.' Format], Format);
end
if count >= No_snapshot
break;
end
end
closepreview;
delete(vidobj);
% =========================================================================
PathName = 'G:\capture_video\movie1\';
obj=VideoWriter(date_string_vid,'Grayscale AVI');
open(obj)
for m=1:No_snapshot
m1=imread([PathName,num2str(m),'.bmp']);
% m1=double(m1(:,:,1));
F = im2frame(m1);
aviObject = addframe(obj,F); % Add the frame to the AVI file
end
close(obj)

Related

Rename images same as video

I saved one frame from each video. I want to rename the frame as the video, but I'm not sure how.
import cv2
import os
def video2frames(video_path, output_path,f_num):
if not os.path.exists(output_path):
os.makedirs(output_path)
cap = cv2.VideoCapture(video_path)
index = 0
while cap.isOpened():
Ret, Mat = cap.read()
if Ret:
index += 1
if index != f_num:
continue
cv2.imwrite(output_path + '/' + str(index) + '.png', Mat)
else:
break
cap.release()
return
def multiple_video2frames( video_path, output_path, f_num ):
list_videos = os.listdir(video_path)
for video in list_videos:
video_base = os.path.basename(video)
input_file = video_path + '/' + video
out_path = output_path + '/' + video_base
video2frames(input_file, out_path, f_num)
return
# run all
video_path = 'videos' # all videos
output_path = 'final' # location on ur pc
multiple_video2frames( video_path, output_path, 300 )
Searched: How can I extract and save image frames from a large number of videos all at once using OpenCV Python?

resolving out of memory error in MAT LAB

In my code written for fractal image compression I got an error as :
Out of memory. Type HELP MEMORY for your options.
Error in tformarray (line 228)
B(prod(fsize_B)) = A(1);
Error in imtransform (line 275)
B = tformarray(args.A, args.tform, args.resampler, tdims_a, tdims_b, ...
Error in test1_UI (line 85)
I = imtransform(I,tform);
How can i resolve this?
my code where this happens is as follows :
[optimizer, metric] = imregconfig('monomodal');
% find the affine transformation from the damain block to range block
for rR=1:nrR
for cR=1:ncR
i=1;
for rd=1:nrD
for cd=1:ncD
s(i)= ssim(caR{rR,cR},imresize(caD{rd,cd},[64 64]));
if s(i)== d(rR,cR)
tformO = imregtform(caD{rd,cd},caR{rR,cR},'affine',optimizer,metric);
T(rR,cR) = tformO;
else
i=i+1;
end
end
end
d(rR,cR) = max(s);
end
end
clear d
% A - any initial image
A = imread('lena_jpgx80.jpg');
I = A;
for rR=1:nrR
for cR=1:ncR
tform = maketform('affine',T(rR,cR).T);
I = imtransform(I,tform);
i=i+1;
end
end
imshow(I)

How to create video from still images in MATLAB?

I am new to MATLAB. I am trying to encrypt video file in MATLAB. I encrypted the individual frame of video. I am using MATLAB 7.10.0 (R2010a) , that's why I used "mmreader" fumction. But now I am not getting how to reassemble all the encrypted frames into a new video. here is my code,
vid = mmreader('videoSampl.avi');
numFrame = vid.NumberOfframes;
for i = 1:2:3
frame = read(vid, i);
gray = rgb2gray(frame);
n = numel(gray);
plaintext = reshape(gray, n, 1);
cipherImg = cipher (plaintext, w, s_box, poly_mat, 1);
re_plaintext = inv_cipher (cipherImg, plaintext, w, inv_s_box, inv_poly_mat, 1);
img = reshape(cipherImg, 128, 128);
imwrite(img,['videoaes/encrypted/image' int2str(i), '.jpg']);
imgP = reshape(re_plaintext, 128, 128);
imwrite(imgP,['videoaes/decrypted/Dimage' int2str(i), '.jpg']);
im(i)=image(frames);
end
I have two folders encrypted and decrypted, I want to convert these folders into avi video again.
Here is the code to convert video from ur encrypted images
ImagesFolder=uigetdir;
jpegFiles = dir(strcat(ImagesFolder,'\*.png'));
S = [jpegFiles(:).datenum];
[S,S] = sort(S);
jpegFilesS =jpegFiles(S);
VideoFile=strcat(ImagesFolder,'\MyVideo');writerObj=VideoWriter(VideoFile);
fps= 10; writerObj.FrameRate = fps;
open(writerObj);
fort=1:length(jpegFilesS)Frame=imread(strcat(ImagesFolder,'\',jpegFilesS(t).name))writeVideo(writerObj,im2frame(Frame))endclose(writerObj;

FFmpeg: bitrate change dynamically

I read the previous thread and this is the response from NISHAnT,
FFMPEG: Dynamic change of bit_rate for Video
avcodec_init();
avcodec_register_all();
codec = avcodec_find_encoder(CODEC_ID_H263);
c = avcodec_alloc_context();
picture= avcodec_alloc_frame();
c->bit_rate = bitrate;
c->width = w;
c->height = h;
c->time_base= (AVRational){1,framerate};
c->pix_fmt = PIX_FMT_YUV420P;
avcodec_close(c);
av_free(c);
And this is my code:
if(previous_BR != cur_BR){
previous_BR = cur_BR;
AVCodecContext* new_c = av_mallocz(sizeof(AVCodecContext));;
avcodec_copy_context(new_c, ost_table[0]->st->codec);
avcodec_close(ost_table[0]->st->codec);
av_free(ost_table[0]->st->codec);
avcodec_init();
avcodec_register_all();
ost_table[0]->enc = avcodec_find_encoder(CODEC_ID_H264);
new_c = avcodec_alloc_context3(ost_table[0]->enc);
ost_table[0]->st->codec = new_c;
AVFrame *picture= avcodec_alloc_frame();
new_c->bit_rate = cur_BR;
new_c->width = 352;
new_c->height = 288;
int framerate = 30;
new_c->time_base= (AVRational){1,framerate};
new_c->pix_fmt = PIX_FMT_YUV420P;
new_c->codec_type = AVMEDIA_TYPE_VIDEO;
new_c->codec_id = CODEC_ID_H264;}
I tried to add my code to transcode(), but ffmpeg exits after it goes through my codes.
is there something wrong with my codes?
or what else I should add?
I put the code after "redo:", so that it will recursively loop back.
please help !!
Thank you.
c is AVCodecContext Structure.
You must configure ffmpeg first for the type of file you are playing.Build it by conifguing first build.sh file in ffmpeg root directory.
for the type of file you have to configure the codec9coder-decoder) and muxer/demuxer.
for example to play avi file , you have to configure the muxer/demuxer and codec for avi which is MPEG "AVI" amd "MPEG4" respectively.

How to read large matrix from a csv efficiently in Octave

There are many reports of slow performance of Octave's dlmread. I was hoping that this was fixed in 3.2.4, but when I tried to load a csv file that has a size of ca. 8 * 4 mil (32 mil in total), it also took very, very long time. I searched the web but could not find a workaround for this. Does anybody know a good workaround?
I experienced the same problem and had R handy, so my solution was to use "read.csv" in R, and then use the R package "R.matlab" to write a ".mat" file, and then load that in Octave.
"read.csv" can be pretty slow too, but this worked very well in my case.
The reason is that Octave has a bug that adding data to a very large matrix takes more time then adding the same amount of data to a small matrix.
Below is my try. I choose to save data each 50000 lines, so meanwhile I could already take a look instead of being forced to wait. It is slower for small files, but much faster for larger files.
function alldata = load_data(filename)
fid = fopen(filename,'r');
s=0;
data=[];
alldata=[];
save "temp.mat" alldata;
if fid == -1
disp("Couldn't find file mydata");
else
while (~feof(fid))
line = fgetl(fid);
[t1,t2,t3,t4,d] = sscanf(line,'%i:%i:%i:%i %f', "C"); #reading time as hh:mm:ss:ms and data as float
s++;
t = (t1 * 3600000 + t2 * 60000 + t3 * 1000 + t4);
data = [data; t, d];
if (mod(s,10000) == 0)
#disp(s), disp(" "), disp(t), disp(" "), disp(d), disp("\n");
disp(s);
fflush(stdout);
end
if (mod(s,50000) == 0)
load "temp.mat";
alldata=[alldata; data];
data=[];
save "temp.mat" alldata;
disp("data saved");
fflush(stdout);
end
end
disp(s);
load "temp.mat";
alldata=[alldata; data];
save "temp.mat" alldata;
disp("data saved");
fflush(stdout);
end
fclose(fid);
Here is a workaround that I am using.
I did not find that sscanf will parse input lines as indicated above. Also, I didn't use the temp file.
My .csv file has a large number of rows. They begin with a header of 18 lines and are followed by a data block, each of which has 135 columns. The following code has been tested. My file also begins each row with a dd/mm/yyyy hh:mm field. This will also catch poor lines and indicate where they are by using try/catch.
My .csv file came from a customer who dumped his PARCView load in an Excel file.
function [tags,descr,alldata] = fbcsvread(filename)
fid = fopen(filename,'r');
s = 0;
data=[];
alldata=zeros(1,135);
if fid==-1
disp("Couldn't find file %s\n",filename);
else
linecount = 1;
while (~feof(fid))
line = fgetl(fid);
data2 = zeros(1,135);
if linecount == 1
tags = strsplit(line,",");
elseif linecount == 2
descr = strsplit(line,",");
elseif linecount >= 19
data = strsplit(line,",");
datetime = strsplit(char(data(1))," ");
modyyr = strsplit(char(datetime(1)),"/");
hrmin = strsplit(char(datetime(2)),":");
year1 = sscanf(char(modyyr(3)),"%d","C");
day1 = sscanf(char(modyyr(2)),"%d","C");
month1 = sscanf(char(modyyr(1)),"%d","C");
hour1 = sscanf(char(hrmin(1)),"%d","C");
minute1 = sscanf(char(hrmin(2)),"%d","C");
realtime = datenum(year1,month1,day1,hour1,minute1);
data2(1) = realtime;
for location = 2:134
try
data2(location) = sscanf(char(data(location)),"%f","C");
catch
printf("Error at %s %s\n",char(datetime(1)),char(datetime(2)) );
fflush(stdout);
end_try_catch
endfor
alldata(linecount-18,:) = data2;
if mod(linecount,50) == 0
printf(".");
fflush(stdout);
endif
endif
linecount = linecount + 1;
endwhile
fclose(fid);
endif
endfunction

Resources