MatLab (Image Processing, Image Acquisition) How to save captured images by webcam without overwriting the original file name? - image

I want to save images without overwriting them whenever I hit the pushbutton. Can you please help me how save images without overwriting the original? What I want to do is whenever I'll hit the pushbutton, It will generated 1 image at a time without deleting the original.
Just like in digital cameras, whenever I will hit the trigger button, it will save 1 image and the file name will be image1.jpg. So basically, if I will push trigger again, it will capture 1 image again and the file name will be image2.jpg and so on.
here is my code:
counter = 1; %initialize filename increment
vid = videoinput('winvideo',2);
set(vid, 'ReturnedColorSpace', 'RGB');
img = getsnapshot(vid);
imshow(img);
savename = strcat('C:\Users\Sony Vaio\Documents\Task\images\image_' ,num2str(counter), '.jpg'); %this is where and what your image will be saved
imwrite(img, savename);
counter = counter +1; %counter should increment each time you push the button
My code saves and keeps on overwriting the filename image1.jpg.
To make things clear
1 push to the pushbutton, 1 image saves.
it's like it will call the whole block code every hit at pushbutton.
I hope you guys can help me. I really troubled right now :(
Thank you :)

If this is the code that makes up the callback function for that pushbutton, then yes indeed, it will execute the entire block every time you push it.
If that is the case, you'll need to change it to this:
%// initialize filename increment
persistent counter;
if isempty(counter)
counter = 1; end
vid = videoinput('winvideo', 2);
set(vid, 'ReturnedColorSpace', 'RGB');
img = getsnapshot(vid);
imshow(img);
%// this is where and what your image will be saved
savename = [...
'C:\Users\Sony Vaio\Documents\Task\images\image_', ...
num2str(counter), '.jpg'];
imwrite(img, savename);
%// counter should increment each time you push the button
counter = counter + 1;
or, you could check what files are actually present, and use the next logical filename in the sequence:
vid = videoinput('winvideo', 2);
set(vid, 'ReturnedColorSpace', 'RGB');
img = getsnapshot(vid);
imshow(img);
%// this is where and what your image will be saved
counter = 1;
baseDir = 'C:\Users\Sony Vaio\Documents\Task\images\';
baseName = 'image_';
newName = [baseDir baseName num2str(counter) '.jpg'];
while exist(newName,'file')
counter = counter + 1;
newName = [baseDir baseName num2str(counter) '.jpg'];
end
imwrite(img, newName);

Every time you push that button the counter value resets to 1 because of the very first statement:
counter = 1
and hence the error.
counter = length(dir('*.jpg')) + 1; %Counts the number of .jpg files in the directory
That should do the job.

Zaher:
I'm online program about image processing and image acquisition from the camera in writing MATLAB.
When receiving the image every few seconds I get a picture of the camera.
Photos must be stored and processed in statistical process control charts.
When the first image after image acquisition program hangs and stops.
Please code to get images every 10 seconds online from cameras send images that can be used in statistical process control.
Thank

Related

Writing Macro in ImageJ to open, change color, adjust brightness and resave microscope images

I'm trying to write a code in Image J that will:
Open all images in separate windows that contains "488" within a folder
Use look up tables to convert images to green and RGB color From ImageJ, the commands are: run("Green"); and run("RGB Color");
Adjust the brightness and contrast with defined values for Min and Max (same values for each image).
I know that the code for that is:
//run("Brightness/Contrast..."); setMinAndMax(value min, value max); run("Apply LUT");
Save each image in the same, original folder , in Tiff and with the same name but finishing with "processed".
I have no experience with Java and am very bad with coding. I tried to piece something together using code I found on stackoverflow and on the ImageJ website, but kept getting error codes. Any help is much appreciated!
I don't know if you still need it, but here is an example.
output_dir = "C:/Users/test/"
input_dir = "C:/Users/test/"
list = getFileList(input_dir);
listlength = list.length;
setBatchMode(true);
for (z = 0; z < listlength; z++){
if(endsWith(list[z], 'tif')==true ){
if(list[z].contains("488")){
title = list[z];
end = lengthOf(title)-4;
out_path = output_dir + substring(title,0,end) + "_processed.tif";
open(input_dir + title);
//add all the functions you want
run("Brightness/Contrast...");
setMinAndMax(1, 15);
run("Apply LUT");
saveAs("tif", "" + out_path + "");
close();
};
run("Close All");
}
}
setBatchMode(false);
I think it contains all the things you need. It opens all the images (in specific folder) that ends with tif and contains 488. I didn't completely understand what you want to do with each photo, so I just added your functions. But you probably won't have problems with adding more/different since you can get them with macro recorder.
And the code is written to open tif files. If you have tiff just be cerful that you change that and also change -4 to -5.

Use imwrite to save processed images to different folder in Matlab

I need help with saving processed images to different folder with imwrite.
Currently, I can save all processed images to a single folder.
Img_filename=ls('C:\Users\User\Desktop\Guanlin_CNN1D\CNN1D\GF_BSIF\*.jpg');
imageSize = size(Img_filename);
Img_filenum = size(Img_filename,1);
for img=1:Img_filenum
img_temp=double((rgb2gray(imread(Img_filename(img,:)))));
-----------processing--------
count = count+1;
FileName = fullfile('C:\Users\User\Desktop\Guanlin_CNN1D\CNN1D\GF_BSIF\folder_1',sprintf('%03d_circle_cropped.jpg',count));
imwrite(MM, FileName)
end
However, I have 1000 different images in 1 folder and after processing, it will generate 500 images and I want to save the first 500 processed images into folder_1. And the second 500 processed images to folder_2 and the third 500 images to folder_3 and so on...
How to re-write the imwrite function?
Thank you!
The root folder I used here is named Image_Folder and resides on the desktop. The output folders are named Folder_1, Folder_2 and Folder_3 and also reside on the desktop. I used two nested loops to control the saving of the images. The outer loop controls which folder to write to and the inner loop controls the writing images 1 through 500. The variable Image_File_Names can be used to access the input image file names.
%Folder holding the 1000 images%
Image_Path = "/Users/michael/Desktop/Image_Folder";
%Prefix path for output folders%
Export_Path = "/Users/michael/Desktop/Folder_";
%Adding path with input images%
addpath(Image_Path);
%Listing all images in folder directory%
Image_File_Names = ls(Image_Path);
Image_File_Names = split(Image_File_Names);
Number_Of_Images = length(Image_File_Names) - 1;
for Folder_Index = 1: 3
Export_Folder_Path = Export_Path + num2str(Folder_Index) + "/";
mkdir(Export_Folder_Path);
for Image_Index = 1: 500
%Grab the images as needed%
Input_Image_Index = 1; %Change this index to another variable to grab images within input folder%
Image = imread(string(Image_File_Names(Input_Image_Index)));
%***************************************%
%PROCESS IMAGE%
%***************************************%
%***************************************%
Output_File_Path = Export_Folder_Path + "Image_" + num2str(Image_Index) +".jpg";
imwrite(Image,Export_Folder_Path+num2str(Image_Index)+".jpg");
end
end
Using MATLAB version: R2019b

WriteVideo Matlab

I am trying to write some code to take images from a uEye camera and store them in an avi file. Basically a time lapse. The idea is take 10 images every 10 minutes. I wrote a function with the a timer and a callback function to take the images and store them in the avi file created.
This is how the main function looks like:
vid = videoinput('winvideo', 1, 'RGB24_2048x2048');
vwObj = VideoWriter('timelapsevideo.avi', 'Uncompressed AVI');
vwObj.FrameRate =1;
open(vwObj);
t = timer('ExecutionMode', 'FixedRate', ...
'Period', 2, 'TasksToExecute',2, ...
'TimerFcn', #timelapse_timer);
start(t);
delete(t);
The timer is not specified for 10 pictures every 10 minutes but this is not my problem.
The callback function looks like this:
function timelapse_timer(vid, event) %#ok
utilpath = fullfile(matlabroot, 'toolbox', 'imaq', 'imaqdemos', 'helper');
addpath(utilpath);
vid = videoinput('winvideo', 1, 'RGB24_2048x2048');
start(vid);
img=getdata(vid, 1, 'native', 'numeric');
% imwrite(img, 'example.jpeg')
vwObj = vid.UserData;
writeVideo(vwObj, img);
close(vwObj);
end
I can take one image and write it so the getdata works. The problem is that it does not write it in the avi file created giving me the next error:
Error while evaluating TimerFcn for timer 'timer-1'
Undefined function 'writeVideo' for input arguments of type 'uint8'.
I have done changes like converting the image taken to gray scale but still the same problem.
Thank you in advance for your help
Juan

Transferring a directory contains images in RGB to grayscale

Reading the content of the directory and for every JPEG image converting to grey scale
srcFiles = dir('R:\...\images - Copy\*.jpeg');
for i = 1 : length(srcFiles)
filename = srcFiles(i).name;
try
I = imread(filename);
catch ME
continue
end
IGrey = rgb2gray(I);
imshow(IGrey);
pathOfNewFile = strcat(pathOfGSFolder,filename,'jpeg');
imwrite(IGrey,pathOfNewFile,'jpeg');
end
'R:\...\images - Copy\' is not a valid path. A folder cannot be called ...
When trying to execute the first line you will probably get an error and the variable srcFiles will be empty, so the length of this variable will be 0 and therefore the loop will not execute.

Making a gif from images

I have a load of data in 100 .sdf files (labelled 0000.sdf to 0099.sdf), each of which contain a still image, and I'm trying to produce a .gif from these images.
The code I use to plot the figure are (in the same directory as the sdf files):
q = GetDataSDF('0000.sdf');
imagesc(q.data');
I've attempted to write a for loop that would plot the figure and then save it with the same filename as the sdf file but to no avail, using:
for a = 1:100
q=GetDataSDF('0000.sdf');
fh = imagesc(q.dist_fn.x_px.Left.data');
frm = getframe( fh );
% save as png image
saveas(fh, 'current_frame_%02d.jpg');
end
EDIT: I received the following errors when trying to run this code:
Error using hg.image/get
The name 'Units' is not an accessible property for an instance of class 'image'.
Error in getframe>Local_getRectanglesOfInterest (line 138)
if ~strcmpi(get(h, 'Units'), 'Pixels')
Error in getframe (line 56)
[offsetRect, absoluteRect, figPos, figOuterPos] = ...
Error in loop_code (line 4)
frm = getframe( fh );
How do I save these files using a for loop, and how do I then use those files to produce a movie?
The reason for the error is that you pass an image handle to getframe, but this function excpects a figure handle.
Another problem is that you always load the same file, and that you saveas will not work for gifs. (For saving figures as static images, maybe print is the better option?)
I tried to modify my own gif-writing loop so that it works with your data. I'll try to be extra explicit in the comments, since you seem to be starting out. Remember, you can always use help name_of_command to display a short Matlab help.
% Define a variable that holds the frames per second your "movie" should have
gif_fps = 24;
% Define string variable that holds the filename of your movie
video_filename = 'video.gif';
% Create figure 1, store the handle in a variable, you'll need it later
fh = figure(1);
for a = 0:99
% Prepare file name so that you loop over the data
q = GetDataSDF(['00' num2str(a,'%02d') 'sdf']);
% Plot image
imagesc(q.dist_fn.x_px.Left.data');
% Force Matlab to actually do the plot (it sometimes gets lazy in loops)
drawnow;
% Take a "screenshot" of the figure fh
frame = getframe(fh);
% Turn screenshot into image
im = frame2im(frame);
% Turn image into indexed image (the gif format needs this)
[imind,cm] = rgb2ind(im,256);
% If first loop iteration: Create the file, else append to it
if a == 0;
imwrite(imind,cm,video_filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,video_filename,'gif','WriteMode','append','DelayTime',1/gif_fps);
end
end
One more note: When the size of the data is the same for each plot, it makes sense to only use the plot(or in this case, imagesc) command once, and in later loop iterations replace it with a set(ah,'Ydata',new_y_data) (or in this case set(ah,'CData',q.dist_fn.x_px.Left.data'), where ah is a handle of the plot axes (not the plot figure!). This is orders of magnitude faster than creating a whole new plot in each loop iteration. The downside is that the scaling (here, the color-scaling) will be the same for each plot. But in every case that I have worked on so far, that was actually desirable.

Resources