Skip to content

Instantly share code, notes, and snippets.

@imunro
Forked from bramalingam/Micromanager_Matlab_OMERO.m
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save imunro/665c47f203deedebd439 to your computer and use it in GitHub Desktop.

Select an option

Save imunro/665c47f203deedebd439 to your computer and use it in GitHub Desktop.
function [img_grid] = grid_calculator(x,y,fs,nf,nwx,nwy,xwd,ywd)
%ex usage for a 96 well plate,9 fields being imaged with a interfield
%distance of 200 microns.
% img_grid = grid_calculator(0,0,200,9,12,8,9000,9000);
% x: Stage x position
% y: Stage y position
% fs: Intra-well field spacing
% nf: Number of fields per well
% nwx: number of wells in the x direction or number of columns in your plate (12 in the case of 96 wells).
% nwx: number of wells in the y direction or number of rows in your
% plate (12 in the case of 96 wells).
% xwd: Centroid to centroid distance between adjacent wells in the x
% direction (Inter column spacing).
% ywd: Centroid to centroid distance between adjacent wells in the y
% direction (Inter row spacing).
xgrid=(x-fs*nf):fs:(x+fs*nf);
ygrid=(y-fs*nf):fs:(y+fs*nf);
resvec=[];
for i=1:length(xgrid)
xval=xgrid(i);
for j=1:length(ygrid)
yval=ygrid(j);
resvec=[resvec ; xval yval x y ((x-xval)^2+(y-yval)^2)^0.5];
end
end
[aa ii]=sort(resvec(:,5)); %#ok<*ASGLU>
img_grid=resvec(ii(1:nf),1:2);
xvec=repmat([0:xwd:(nwx-1)*xwd]',1,size(img_grid,1))';
xa1=repmat(img_grid(:,1),1,size(xvec,2));
xvec=xvec+xa1;
yvec=repmat(img_grid(:,2),1,size(xvec,2));
xvec=reshape(xvec,[],1);yvec=yvec(:);
yval=repmat([0:ywd:(nwy-1)*ywd]',1,size(yvec,1))';yval=yval(:);
rowvec=[xvec yvec];rowvec=repmat(rowvec,nwy,1);
img_grid=[rowvec(:,1) rowvec(:,2)+yval];
%Multiple sites imaging
%and image analysis(identifying cells with a circularity index>0.8)
%feedback, based on number of cells, change objective to check assay qc
%Author : Balaji.R
%Help : http://micro-manager.3463995.n2.nabble.com/saving-a-multi-image-file-programmatically-td7578824.html
%Init
clear all;close all;
%Import packages
import org.micromanager.MMStudioMainFrame;
import org.micromanager.acquisition.AcquisitionWrapperEngine;
import ij.io.FileSaver;
import org.micromanager.utils.ImageUtils;
import ij.process.ImageProcessor;
import ij.ImagePlus;
%Create gui object
gui = MMStudioMainFrame(false);
%clear all previous acquisitions
gui.closeAllAcquisitions();
gui.clearMessageWindow();
%Show Gui
f = warndlg('Press ok once config file is loaded', 'Note');
gui.show
drawnow;waitfor(f);
%file locations
acqName = 'test-acq';
rootDirName = '/Applications/Micro-Manager1.4/test/';
mkdir(rootDirName)
%parameters
exposures = [10, 1000];
fields = 6;
%Create objects (Acquisition engine and core object)
mmc = gui.getCore;
acq = gui.getAcquisitionEngine;
%load config
mmc.loadSystemConfiguration ('/Applications/Micro-Manager1.4/MMConfig_demo.cfg');
%Get config's of devices
stage=mmc.getXYStageDevice();
zdrive=mmc.getFocusDevice();
%Get position of X,Y and Z
X1= mmc.getXPosition(stage);
Y1= mmc.getYPosition(stage);
Z1=mmc.getPosition(zdrive); %Manually focus on the first field
%load camera properties
config_groups=mmc.getAvailableConfigGroups();
% read_rate=config_groups.get(5);
objective_turr=mmc.getAvailableConfigs(config_groups.get(4));
light_path=mmc.getAvailableConfigs(config_groups.get(3));
Gain_multipler=config_groups.get(2);
channels=mmc.getAvailableConfigs(config_groups.get(1));
camera_gain=config_groups.get(0);
%Set light path (To camera view)
mmc.setConfig(config_groups.get(3), light_path.get(1));
%stage movement in microns (Field spacing)
rval1=100;rval=X1;
%OMERO Session
%Params
host= 'localhost'; %Host address
username = 'username'; %Username for Insight
password = 'password'; %Password for Insight
folder_depth_bioformats=10;
ProjectName = 'Test';
DatasetName = 'Test1';
%Load Omero
client = loadOmero(host);
session = client.createSession(username, password);
client.enableKeepAlive(60);
%Import type for Omero (1 for Symlink Transfer/inplace-import, any other numeric value for
%regular upload)
importopt = 1;
%Image Output Directory and Suffix for Image Name
acqRoot = [pwd '/'];
BrightAcqName = 'Test_Config.tiff';
%Temporary Params
Wells={'A' 'B' 'C' 'D'};
Fields = {'F'};
cntr1=1;resvec=[];cellcntr=0;
for l=1:2
mmc.setXYPosition(stage, rval, Y1);
mmc.waitForDevice(stage);
for k=1:3
if k>1
rval=rval1+mmc.getXPosition(stage);
else
rval=mmc.getXPosition(stage);
end
cntr=1;rvec=[];
mmc.setPosition(zdrive,(Z1));
mmc.setExposure(exposures(1));
mmc.setConfig(config_groups.get(1), channels.get(0));
mmc.setXYPosition(stage, rval, Y1);
mmc.waitForDevice(stage);
mmc.snapImage();
img = mmc.getImage(); % returned as a 1D array of signed integers in row-major order
width = mmc.getImageWidth();
height = mmc.getImageHeight();
%Saving image
proc0 = ImageUtils.makeProcessor(mmc, img);
imgp0 = ImagePlus('',proc0);
fs = FileSaver(imgp0);
path=[acqRoot Wells{1} '00' num2str(l) Fields{1} '00' num2str(k) '_' BrightAcqName];
fs.saveAsTiff(path);
if mmc.getBytesPerPixel == 2
pixelType = 'uint16';
else
pixelType = 'uint8';
end
img = typecast(img, pixelType); % pixels must be interpreted as unsigned integers
img = transpose(reshape(img, [width, height])); % image should be interpreted as a 2D array
img1(:,:,cntr,cntr1) = img;
% imshow(imadjust(img))
pause(3)
%Upload Image to the OMERO Server
upload_image(path,session,username,password,ProjectName,DatasetName,host,importopt)
cntr1=cntr1+1;
% [seg_img clustidx]=kmeans(double(img(:)),3,'emptyaction','drop');
% idx1=find(clustidx==min(clustidx));
%
% [aa numcells]=bwlabel(bwareaopen(reshape(seg_img==idx1,512,512),15));
% props = regionprops(aa, 'Area', 'Perimeter');
% areas = [props.Area];
% perims = [props.Perimeter];
% circularities = 4 * pi * areas ./ perims .^ 2; % formula for circularity index
%
% remidx=find(circularities<=0.80);
% [finimg numcells]=bwlabel(~ismember(aa,[0 remidx]));
%
% stagevec(k,:)=[rval Y1 Z1 numcells];
% cellcntr=cellcntr+numcells;
% imwrite(img,[rootDirName acqName '_field_' num2str(k) '.tiff'],'Compression','none')
% if cellcntr>=70
% break
% end
end
end
%Stitch all images together (QC View)
% montage(img1);imcontrast;
% figure;imagesc(stagevec(:,4));caxis([0 100])
% %Move stage to field with minimum cells and change objectives and snap an
% %image
% idx1=find(stagevec(:,4)==min(stagevec(:,4)));
% mmc.setXYPosition(stage, stagevec(idx1,1), Y1);
% mmc.waitForDevice(stage);
% %change objectives line
% curr_obj=objective_turr.get(0);
% mmc.setConfig(config_groups.get(4), curr_obj);
% mmc.snapImage();
% img = mmc.getImage(); % returned as a 1D array of signed integers in row-major order
% width = mmc.getImageWidth();
% height = mmc.getImageHeight();
%
% if mmc.getBytesPerPixel == 2
% pixelType = 'uint16';
% else
% pixelType = 'uint8';
% end
%
% img = typecast(img, pixelType); % pixels must be interpreted as unsigned integers
% img = transpose(reshape(img, [width, height])); % image should be interpreted as a 2D array
% imshow(imadjust(img));title('10x image');
clear all;close all;
inputdir=[pwd '/plugins/Micro-Manager'];
javaaddpath([pwd '/ij.jar']);
jars1=dir(inputdir);
for i=3:length(jars1)
javaaddpath([inputdir '/' jars1(i).name]);
end
inputdir=['/Users/bramalingam/Downloads/OMERO.matlab-5.0.1-969-10a1148-ice33-b658'];
addpath(genpath(inputdir));
jars1=dir([inputdir '/libs']);
for i=3:length(jars1)
javaaddpath([inputdir '/libs/' jars1(i).name]);
end
% Remove the occurances of string s2 from string s1
% Input:
% s1 - big string
% s2 - forbidded string to be removed
%
% Output:
% s - string containing s1 without s2
%
function s = strdiff(s1, s2)
n = length(s2);
f = strfind(s1, s2); % find all occurances of 2nd string in 1st string
if(~isempty(f))
bad_inds = f;
for i=1:n-1
bad_inds = union(bad_inds, f+i);
end
good_inds = setdiff(1:length(s1), bad_inds);
s = s1(good_inds);
else % don't change the string
s = s1;
end
function upload_image(path,session,username,password,ProjectName,DatasetName,host,importopt)
%Import Packages
import loci.formats.in.DefaultMetadataOptions;
import loci.formats.in.MetadataLevel;
import loci.common.*;
import ome.formats.OMEROMetadataStoreClient;
import ome.formats.importer.*;
import ome.formats.importer.ImportConfig;
import ome.formats.importer.cli.ErrorHandler;
import ome.formats.importer.cli.LoggingImportMonitor;
import omero.model.Dataset;
import omero.model.DatasetI;
import ome.services.blitz.repo.*;
import ome.formats.importer.transfers.*;
import ome.formats.importer.transfers.SymlinkFileTransfer;
import ome.formats.importer.cli.CommandLineImporter;
import java.util.prefs.*;
%Choose a dataset name, will be assigned to your imported dataset under the root user.
DataForImport = path;%Source Directory
%Logging (switch on)
loci.common.DebugTools.enableLogging('DEBUG');
%Configuration Object
config = ImportConfig();
%Set Config params
config.email.set('');
config.sendFiles.set(true);
config.sendReport.set(false);
config.contOnError.set(false);
config.debug.set(false);
config.hostname.set(host);
port = javaObject('java.lang.Integer',4064);
config.port.set(port);
config.username.set(username);
config.password.set(password);
config.targetClass.set('omero.model.Dataset');
%Check a project named ProjectName
projects = getProjects(session);
for j=1:numel(projects)
pjname=char(projects(j).getName.getValue());
if ~isempty(strmatch(pjname,ProjectName,'exact'))
project=projects(j);
break
end
end
if j==numel(projects)
project = handle(createProject(session, ProjectName));
end
%Check datasetList under the Project to see if there are datasets with
%similar name
datasetsList = project.linkedDatasetList;
for i = 0:datasetsList.size()-1,
d = datasetsList.get(i);
dname = char(d.getName.getValue());
if ~isempty(strmatch(dname,DatasetName,'exact'))
dataset=d;
break
end
end
if isempty(datasetsList)
dataset = handle(createDataset(session, DatasetName, project.getId.getValue()));
end
dataID = javaObject('java.lang.Long',dataset.getId().getValue());
config.targetId.set(dataID);
%Metadatastore Object
store = config.createStore();
store.logVersionInfo(config.getIniVersionNumber());
reader = OMEROWrapper(config);
%Library Object
if importopt == 1
library = handle(ImportLibrary(store, reader, SymlinkFileTransfer));
else
library = handle(ImportLibrary(store, reader));
end
handler = ErrorHandler(config);
library.addObserver(LoggingImportMonitor());
%Import
paths = DataForImport;
candidates = ImportCandidates(reader, paths, handler);
reader.setMetadataOptions(DefaultMetadataOptions(MetadataLevel.ALL));
success = library.importCandidates(config, candidates);
if success == 0
log = org.apache.commons.logging.LogFactory.getLog('ome.formats.importer.ImportLibrary');
templog=log.setLevel(0);
end
%Logout and close session
store.logout();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment