plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
Vincentqyw/light-field-TB-master
|
LFFindCalInfo.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFFindCalInfo.m
| 2,572 |
utf_8
|
c7daafa528ed72904c233ed5ad834fe6
|
% LFFindCalInfo - Find and load the calibration info file appropriate for a specific camera, zoom and focus
%
% Usage:
%
% [CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions )
%
% This uses a calibration info database to locate a calibration appropriate to a given camera under a given set of zoom
% and focus settings. It is called during rectification.
%
% Inputs:
%
% LFMetadata : loaded from a decoded light field, this contains the camera's serial number and zoom and focus settings.
% RectOptions : struct controlling rectification
% .CalibrationDatabaseFname : name of the calibration file database
%
%
% Outputs:
%
% CalInfo: The resulting calibration info, or an empty array if no appropriate calibration found
% RectOptions : struct controlling rectification, the following fields are added
% .CalInfoFname : Name of the calibration file that was loaded
%
% See also: LFUtilProcessCalibrations, LFSelectFromDatabase
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function [CalInfo, RectOptions] = LFFindCalInfo( LFMetadata, RectOptions )
CalInfo = [];
DesiredCam = struct('CamSerial', LFMetadata.SerialData.camera.serialNumber, ...
'ZoomStep', LFMetadata.devices.lens.zoomStep, ...
'FocusStep', LFMetadata.devices.lens.focusStep );
CalFileInfo = LFSelectFromDatabase( DesiredCam, RectOptions.CalibrationDatabaseFname );
if( isempty(CalFileInfo) )
return;
end
PathToDatabase = fileparts( RectOptions.CalibrationDatabaseFname );
RectOptions.CalInfoFname = CalFileInfo.Fname;
CalInfo = LFReadMetadata( fullfile(PathToDatabase, RectOptions.CalInfoFname) );
fprintf('Loading %s\n', RectOptions.CalInfoFname);
%---Check that the decode options and calibration info are a good match---
fprintf('\nCalibration / LF Picture (ideally these match exactly):\n');
fprintf('Serial:\t%s\t%s\n', CalInfo.CamInfo.CamSerial, LFMetadata.SerialData.camera.serialNumber);
fprintf('Zoom:\t%d\t\t%d\n', CalInfo.CamInfo.ZoomStep, LFMetadata.devices.lens.zoomStep);
fprintf('Focus:\t%d\t\t%d\n\n', CalInfo.CamInfo.FocusStep, LFMetadata.devices.lens.focusStep);
if( ~strcmp(CalInfo.CamInfo.CamSerial, LFMetadata.SerialData.camera.serialNumber) )
warning('Calibration is for a different camera, rectification may be invalid.');
end
if( CalInfo.CamInfo.ZoomStep ~= LFMetadata.devices.lens.zoomStep || ...
CalInfo.CamInfo.FocusStep ~= LFMetadata.devices.lens.focusStep )
warning('Zoom / focus mismatch -- for significant deviations rectification may be invalid.');
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFConvertToFloat.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFConvertToFloat.m
| 481 |
utf_8
|
347631d509cdee15114cff38f1046966
|
% LFConvertToFloat - Helper function to convert light fields to floating-point representation
%
% Integer inputs get normalized to a max value of 1.
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function LF = LFConvertToFloat( LF, Precision )
Precision = LFDefaultVal('Precision', 'single');
OrigClass = class(LF);
IsInt = isinteger(LF);
LF = cast(LF, Precision);
if( IsInt )
LF = LF ./ cast(intmax(OrigClass), Precision);
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFUnpackRawBuffer.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFUnpackRawBuffer.m
| 2,263 |
utf_8
|
6edde771ccfa5abb4c1b0242c9ee9af9
|
% LFUnpackRawBuffer - Unpack a buffer of packed raw binary data into an image
%
% Usage:
%
% ImgOut = LFUnpackRawBuffer( Buff, BitPacking, ImgSize )
%
% Used by LFReadRaw and LFReadLFP, this helper function unpacks a raw binary data buffer in one of several formats.
%
% Inputs :
%
% Buff : Buffer of chars to be unpacked
% BitPacking : one of '12bit', '10bit' or '16bit'; default is '12bit'
% ImgSize : size of the output image
%
% Outputs:
%
% Img : an array of uint16 gray levels. No demosaicing (decoding Bayer pattern) is performed.
%
% See also: LFDecodeLensletImageSimple, demosaic
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function ImgOut = LFUnpackRawBuffer( Buff, BitPacking, ImgSize )
switch( BitPacking )
case '8bit'
ImgOut = reshape(Buff, ImgSize);
case '10bit'
t0 = uint16(Buff(1:5:end));
t1 = uint16(Buff(2:5:end));
t2 = uint16(Buff(3:5:end));
t3 = uint16(Buff(4:5:end));
lsb = uint16(Buff(5:5:end));
t0 = bitshift(t0,2);
t1 = bitshift(t1,2);
t2 = bitshift(t2,2);
t3 = bitshift(t3,2);
t0 = t0 + bitand(lsb,bin2dec('00000011'));
t1 = t1 + bitshift(bitand(lsb,bin2dec('00001100')),-2);
t2 = t2 + bitshift(bitand(lsb,bin2dec('00110000')),-4);
t3 = t3 + bitshift(bitand(lsb,bin2dec('11000000')),-6);
ImgOut = zeros(ImgSize, 'uint16');
ImgOut(1:4:end) = t0;
ImgOut(2:4:end) = t1;
ImgOut(3:4:end) = t2;
ImgOut(4:4:end) = t3;
case '12bit'
t0 = uint16(Buff(1:3:end));
t1 = uint16(Buff(2:3:end));
t2 = uint16(Buff(3:3:end));
a0 = bitshift(t0,4) + bitshift(bitand(t1,bin2dec('11110000')),-4);
a1 = bitshift(bitand(t1,bin2dec('00001111')),8) + t2;
ImgOut = zeros(ImgSize, 'uint16');
ImgOut(1:2:end) = a0;
ImgOut(2:2:end) = a1;
case '16bit'
t0 = uint16(Buff(1:2:end));
t1 = uint16(Buff(2:2:end));
a0 = bitshift(t1, 8) + t0;
ImgOut = zeros(ImgSize, 'uint16');
ImgOut(:) = a0;
otherwise
error('Unrecognized bit packing');
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFCalFindCheckerCorners.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFCalFindCheckerCorners.m
| 8,815 |
utf_8
|
52b7cb09809df1fe8683b8964e71a159
|
% LFCalFindCheckerCorners - locates corners in checkerboard images, called by LFUtilCalLensletCam
%
% Usage:
% CalOptions = LFCalFindCheckerCorners( InputPath, CalOptions )
% CalOptions = LFCalFindCheckerCorners( InputPath )
%
% This function is called by LFUtilCalLensletCam to identify the corners in a set of checkerboard
% images.
%
% Inputs:
%
% InputPath : Path to folder containing decoded checkerboard images.
%
% [optional] CalOptions : struct controlling calibration parameters, all fields are optional
% .CheckerCornersFnamePattern : Pattern for building output checkerboard corner files; %s is
% used as a placeholder for the base filename
% .LFFnamePattern : Filename pattern for locating input light fields
% .ForceRedoCornerFinding : Forces the function to run, overwriting existing results
% .ShowDisplay : Enables display, allowing visual verification of results
%
% Outputs :
%
% CalOptions struct as applied, including any default values as set up by the function
%
% Checker corner files are the key outputs of this function -- one file is generated fore each
% input file, containing the list of extracted checkerboard corners.
%
% See also: LFUtilCalLensletCam, LFCalInit, LFCalRefine
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function CalOptions = LFCalFindCheckerCorners( InputPath, CalOptions )
%---Defaults---
CalOptions = LFDefaultField( 'CalOptions', 'ForceRedoCornerFinding', false );
CalOptions = LFDefaultField( 'CalOptions', 'LFFnamePattern', '%s__Decoded.mat' );
CalOptions = LFDefaultField( 'CalOptions', 'CheckerCornersFnamePattern', '%s__CheckerCorners.mat' );
CalOptions = LFDefaultField( 'CalOptions', 'ShowDisplay', true );
CalOptions = LFDefaultField( 'CalOptions', 'MinSubimageWeight', 0.2 * 2^16 ); % for fast rejection of dark frames
%---Build a regular expression for stripping the base filename out of the full raw filename---
BaseFnamePattern = regexp(CalOptions.LFFnamePattern, '%s', 'split');
BaseFnamePattern = cell2mat({BaseFnamePattern{1}, '(.*)', BaseFnamePattern{2}});
%---Tagged onto all saved files---
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
%---Crawl folder structure locating raw lenslet images---
fprintf('\n===Locating light fields in %s===\n', InputPath);
[FileList, BasePath] = LFFindFilesRecursive( InputPath, sprintf(CalOptions.LFFnamePattern, '*') );
if( isempty(FileList) )
error(['No files found... are you running from the correct folder?\n'...
' Current folder: %s\n'], pwd);
end;
fprintf('Found :\n');
disp(FileList)
%---Check zoom / focus and serial number settings across light fields---
fprintf('Checking zoom / focus / serial number across all files...\n');
for( iFile = 1:length(FileList) )
CurFname = FileList{iFile};
load(fullfile(BasePath, CurFname), 'LFMetadata');
CamSettings(iFile).Fname = CurFname;
CamSettings(iFile).ZoomStep = LFMetadata.devices.lens.zoomStep;
CamSettings(iFile).FocusStep = LFMetadata.devices.lens.focusStep;
CamSettings(iFile).CamSerial = LFMetadata.SerialData.camera.serialNumber;
end
% Find the most frequent serial number
[UniqueSerials,~,SerialIdx]=unique({CamSettings.CamSerial});
NumSerials = size(UniqueSerials,2);
MostFreqSerialIdx = median(SerialIdx);
CamInfo.CamSerial = UniqueSerials{MostFreqSerialIdx};
CamInfo.CamModel = LFMetadata.camera.model;
% Finding the most frequent zoom / focus is easier
CamInfo.FocusStep = median([CamSettings.FocusStep]);
CamInfo.ZoomStep = median([CamSettings.ZoomStep]);
fprintf( 'Serial: %s, ZoomStep: %d, FocusStep: %d\n', CamInfo.CamSerial, CamInfo.ZoomStep, CamInfo.FocusStep );
InvalidIdx = find( ...
([CamSettings.ZoomStep] ~= CamInfo.ZoomStep) | ...
([CamSettings.FocusStep] ~= CamInfo.FocusStep) | ...
(SerialIdx ~= MostFreqSerialIdx)' );
if( ~isempty(InvalidIdx) )
warning('Some files mismatch');
for( iInvalid = InvalidIdx )
fprintf('Serial: %s, ZoomStep: %d, FocusStep: %d -- %s\n', CamSettings(iInvalid).CamSerial, CamSettings(iInvalid).ZoomStep, CamSettings(iInvalid).FocusStep, CamSettings(iInvalid).Fname);
end
fprintf('For significant deviations, it is recommended that these files be removed and the program restarted.');
else
fprintf('...all files match\n');
end
%---enable warning to display it once; gets disabled after first call to detectCheckerboardPoints--
warning('on','vision:calibrate:boardShouldBeAsymmetric');
fprintf('Skipping subimages with mean weight below MinSubimageWeight %g\n', CalOptions.MinSubimageWeight);
%---Process each folder---
SkippedFileCount = 0;
ProcessedFileCount = 0;
TotFileTime = 0;
%---Process each raw lenslet file---
for( iFile = 1:length(FileList) )
CurFname = FileList{iFile};
CurFname = fullfile(BasePath, CurFname);
%---Build the base filename---
CurBaseFname = regexp(CurFname, BaseFnamePattern, 'tokens');
CurBaseFname = CurBaseFname{1}{1};
[~,ShortFname] = fileparts(CurBaseFname);
fprintf(' --- %s [%d / %d]', ShortFname, iFile, length(FileList));
%---Check for already-decoded file---
SaveFname = sprintf(CalOptions.CheckerCornersFnamePattern, CurBaseFname);
if( ~CalOptions.ForceRedoCornerFinding )
if( exist(SaveFname, 'file') )
fprintf( ' already done, skipping\n' );
SkippedFileCount = SkippedFileCount + 1;
continue;
end
end
ProcessedFileCount = ProcessedFileCount + 1;
fprintf('\n');
%---Load the LF---
tic % track time
load( CurFname, 'LF', 'LensletGridModel', 'DecodeOptions' );
LFSize = size(LF);
if( CalOptions.ShowDisplay )
LFFigure(1);
clf
end
fprintf('Processing all subimages');
for( TIdx = 1:LFSize(1) )
fprintf('.');
for( SIdx = 1:LFSize(2) )
% todo[optimization]: once a good set of corners is found, tracking them through s,u
% and t,v would be significantly faster than independently recomputing the corners
% for all u,v slices
CurW = squeeze(LF(TIdx, SIdx, :,:, 4));
CurW = mean(CurW(:));
if( CurW < CalOptions.MinSubimageWeight )
CurCheckerCorners = [];
else
CurImg = squeeze(LF(TIdx, SIdx, :,:, 1:3));
CurImg = rgb2gray(CurImg);
[CurCheckerCorners,CheckBoardSize] = detectCheckerboardPoints( CurImg );
warning('off','vision:calibrate:boardShouldBeAsymmetric'); % display once (at most)
% Matlab's detectCheckerboardPoints sometimes expresses the grid in different orders, especially for
% symmetric checkerbords. It's up to the consumer of this data to treat the points in the correct order.
end
HitCount(TIdx,SIdx) = numel(CurCheckerCorners);
CheckerCorners{TIdx,SIdx} = CurCheckerCorners;
end
%---Display results---
if( CalOptions.ShowDisplay )
clf
for( SIdx = 1:LFSize(2) )
if( HitCount(TIdx,SIdx) > 0 )
CurImg = squeeze(LF(TIdx, SIdx, :,:, 1:3));
CurImg = rgb2gray(CurImg);
NImages = LFSize(2);
NCols = ceil(sqrt(NImages));
NRows = ceil(NImages / NCols);
subplot(NRows, NCols, SIdx);
imshow(CurImg);
colormap gray
hold on;
cx = CheckerCorners{TIdx,SIdx}(:,1);
cy = CheckerCorners{TIdx,SIdx}(:,2);
plot(cx(:),cy(:),'r.', 'markersize',15)
axis off
axis image
axis tight
end
end
truesize([150,150]); % bigger display
drawnow
end
end
fprintf('\n');
%---Save---
fprintf('Saving result to %s...\n', SaveFname);
save(SaveFname, 'GeneratedByInfo', 'CheckerCorners', 'LFSize', 'CamInfo', 'LensletGridModel', 'DecodeOptions');
TotFileTime = TotFileTime + toc;
MeanFileTime = TotFileTime / ProcessedFileCount;
fprintf( 'Mean time per file: %.1f min\n', MeanFileTime/60 );
TimeRemain_s = MeanFileTime * (length(FileList) - ProcessedFileCount - SkippedFileCount);
fprintf( 'Est time remain: ~%d min\n', ceil(TimeRemain_s/60) );
end
fprintf(' ---Finished finding checkerboard corners---\n');
|
github
|
Vincentqyw/light-field-TB-master
|
LFSelectFromDatabase.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFSelectFromDatabase.m
| 2,288 |
utf_8
|
f72e49d5261aad46cd204a67ea981f14
|
% LFSelectFromDatabase - support function for selecting white image/calibration by matching serial/zoom/focus
%
% Usage:
%
% SelectedCamInfo = LFSelectFromDatabase( DesiredCamInfo, DatabaseFname )
%
% This helper function is used when decoding a light field to select an appropriate white image,
% and when rectifying a light field to select the appropriate calibration. It works by parsing a
% database (white image or calibration), and searching its CamInfo structure for the best match to
% the requested DesiredCamInfo. DesiredCamInfo is set based on the camera settings used in
% measuring the light field. See LFUtilDecodeLytroFolder / LFLytroDecodeImage for example usage.
%
% Selection prioritizes the camera serial number, then zoom, then focus. It is unclear whether this
% is the optimal approach.
%
% The output SelectedCamInfo includes all fields in the database's CamInfo struct, including the
% filename of the selected calibration or white image. This facilitates decoding / rectification.
%
% See also: LFUtilProcessWhiteImages, LFUtilProcessCalibrations, LFUtilDecodeLytroFolder, LFLytroDecodeImage
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function SelectedCamInfo = LFSelectFromDatabase( DesiredCamInfo, DatabaseFname )
%---Load the database---
load(DatabaseFname, 'CamInfo');
%---Find the closest to the desired settings, prioritizing serial, then zoom, then focus---
ValidSerial = find( ismember({CamInfo.CamSerial}, {DesiredCamInfo.CamSerial}) );
% Discard non-matching serials
CamInfo = CamInfo(ValidSerial);
OrigIdx = ValidSerial;
% Find closest zoom
ZoomDiff = abs([CamInfo.ZoomStep] - DesiredCamInfo.ZoomStep);
BestZoomDiff = min(ZoomDiff);
BestZoomIdx = find( ZoomDiff == BestZoomDiff ); % generally multiple hits
% Retain the (possibly multiple) matches for the best zoom setting
% CamInfo.ZoomStep = CamInfo(BestZoomIdx).ZoomStep;
CamInfo = CamInfo(BestZoomIdx);
OrigIdx = OrigIdx(BestZoomIdx);
% Of those that are closest in zoom, find the one that's closest in focus
FocusDiff = abs([CamInfo.FocusStep] - DesiredCamInfo.FocusStep);
[~,BestFocusIdx] = min(FocusDiff);
% Retrieve the index into the original
BestOriglIdx = OrigIdx(BestFocusIdx);
SelectedCamInfo = CamInfo(BestFocusIdx);
|
github
|
Vincentqyw/light-field-TB-master
|
LFMapRectifiedToMeasured.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFMapRectifiedToMeasured.m
| 2,589 |
utf_8
|
5e58f495c8db32d93abdde790c719aff
|
% LFMapRectifiedToMeasured - Applies a calibrated camera model to map desired samples to measured samples
%
% Usage:
%
% InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions )
%
% Helper function used by LFCalRectifyLF. Based on a calibrated camera model, including distortion parameters and a
% desired intrinsic matrix, the indices of a set of desired sample is mapped to the indices of corresponding measured
% samples.
%
% Inputs :
%
% InterpIdx : Set of desired indices, in homogeneous coordinates
% CalInfo : Calibration info as returned by LFFindCalInfo
% RectOptions : struct controlling the rectification process, see LFCalRectify
%
% Outputs:
%
% InterpIdx : continuous-domain indices for interpolating from the measured light field
%
% See also: LFCalRectifyLF
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function InterpIdx = LFMapRectifiedToMeasured( InterpIdx, CalInfo, RectOptions )
RectOptions = LFDefaultField( 'RectOptions', 'Precision', 'single' );
%---Cast the to the required precision---
InterpIdx = cast(InterpIdx, RectOptions.Precision);
%---Convert the index of the desired ray to a ray representation using ideal intrinsics---
InterpIdx = RectOptions.RectCamIntrinsicsH * InterpIdx;
%---Apply inverse lens distortion to yield the undistorted ray---
k1 = CalInfo.EstCamDistortionV(1); % r^2
k2 = CalInfo.EstCamDistortionV(2); % r^4
k3 = CalInfo.EstCamDistortionV(3); % r^6
b1 = CalInfo.EstCamDistortionV(4); % decentering of lens distortion
b2 = CalInfo.EstCamDistortionV(5); % decentering of lens distortion
InterpIdx(3:4,:) = bsxfun(@minus, InterpIdx(3:4,:), [b1; b2]); % decentering of lens distortion
%---Iteratively estimate the undistorted direction----
DesiredDirection = InterpIdx(3:4,:);
for( InverseIters = 1:RectOptions.NInverse_Distortion_Iters )
R2 = sum(InterpIdx(3:4,:).^2); % compute radius^2 for the current estimate
% update estimate based on inverse of distortion model
InterpIdx(3:4,:) = DesiredDirection ./ repmat((1 + k1.*R2 + k2.*R2.^2 + k3.*R2.^4),2,1);
end
clear R2 DesiredDirection
InterpIdx(3:4,:) = bsxfun(@plus, InterpIdx(3:4,:), [b1; b2]); % decentering of lens distortion
%---Convert the undistorted ray to the corresponding index using the calibrated intrinsics---
% todo[optimization]: The variable InterpIdx could be precomputed and saved with the calibration
InterpIdx = CalInfo.EstCamIntrinsicsH^-1 * InterpIdx;
%---Interpolate the required values---
InterpIdx = InterpIdx(1:4,:); % drop homogeneous coordinates
|
github
|
Vincentqyw/light-field-TB-master
|
LFCalRefine.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFCalRefine.m
| 16,821 |
utf_8
|
ad30626be45ef6d56dafc860da607c7c
|
% LFCalRefine - refine calibration by minimizing point/ray reprojection error, called by LFUtilCalLensletCam
%
% Usage:
% CalOptions = LFCalRefine( InputPath, CalOptions )
%
% This function is called by LFUtilCalLensletCam to refine an initial camera model and pose
% estimates through optimization. This follows the calibration procedure described in:
%
% D. G. Dansereau, O. Pizarro, and S. B. Williams, "Decoding, calibration and rectification for
% lenslet-based plenoptic cameras," in Computer Vision and Pattern Recognition (CVPR), IEEE
% Conference on. IEEE, Jun 2013.
%
% Minor differences from the paper: camera parameters are automatically initialized, so no prior
% knowledge of the camera's parameters are required; the free intrinsics parameters have been
% reduced by two: H(3:4,5) were previously redundant with the camera's extrinsics, and are now
% automatically centered; and the light field indices [i,j,k,l] are 1-based in this implementation,
% and not 0-based as described in the paper.
%
% Inputs:
%
% InputPath : Path to folder containing decoded checkerboard images. Checkerboard corners must
% be identified prior to calling this function, by running LFCalFindCheckerCorners
% for example. An initial estiamte must be provided in a CalInfo file, as generated
% by LFCalInit. LFUtilCalLensletCam demonstrates the complete procedure.
%
% CalOptions struct controls calibration parameters :
% .Phase : 'NoDistort' excludes distortion parameters from the optimization
% process; for any other value, distortion parameters are included
% .CheckerInfoFname : Name of the file containing the summarized checkerboard
% information, as generated by LFCalFindCheckerCorners. Note that
% this parameter is automatically set in the CalOptions struct
% returned by LFCalFindCheckerCorners.
% .CalInfoFname : Name of the file containing an initial estimate, to be refined.
% Note that this parameter is automatically set in the CalOptions
% struct returned by LFCalInit.
% .ExpectedCheckerSize : Number of checkerboard corners, as recognized by the automatic
% corner detector; edge corners are not recognized, so a standard
% 8x8-square chess board yields 7x7 corners
% .LensletBorderSize : Number of pixels to skip around the edges of lenslets, a low
% value of 1 or 0 is generally appropriate
% .SaveResult : Set to false to perform a "dry run"
% [optional] .OptTolX : Determines when the optimization process terminates. When the
% estimted parameter values change by less than this amount, the
% optimization terminates. See the Matlab documentation on lsqnonlin,
% option `TolX' for more information. The default value of 5e-5 is set
% within the LFCalRefine function; a value of 0 means the optimization
% never terminates based on this criterion.
% [optional] .OptTolFun : Similar to OptTolX, except this tolerance deals with the error value.
% This corresponds to Matlab's lsqnonlin option `TolFun'. The default
% value of 0 is set within the LFCalRefine function, and means the
% optimization never terminates based on this criterion.
%
% Outputs :
%
% CalOptions struct maintains the fields of the input CalOptions, and adds the fields:
%
% .LFSize : Size of the light field, in samples
% .IJVecToOptOver : Which samples in i and j were included in the optimization
% .IntrinsicsToOpt : Which intrinsics were optimized, these are indices into the 5x5
% lenslet camera intrinsic matrix
% .DistortionParamsToOpt : Which distortion paramst were optimized
% .PreviousCamIntrinsics : Previous estimate of the camera's intrinsics
% .PreviousCamDistortion : Previous estimate of the camera's distortion parameters
% .NPoses : Number of poses in the dataset
%
%
% See also: LFUtilCalLensletCam, LFCalFindCheckerCorners, LFCalInit, LFUtilDecodeLytroFolder
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function CalOptions = LFCalRefine( InputPath, CalOptions )
%---Defaults---
CalOptions = LFDefaultField( 'CalOptions', 'OptTolX', 5e-5 );
CalOptions = LFDefaultField( 'CalOptions', 'OptTolFun', 0 );
%---Load checkerboard corners and previous cal state---
CheckerInfoFname = fullfile(InputPath, CalOptions.CheckerInfoFname);
CalInfoFname = fullfile(InputPath, CalOptions.CalInfoFname);
load(CheckerInfoFname, 'CheckerObs', 'IdealChecker', 'LFSize');
[EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CamInfo, LensletGridModel, DecodeOptions] = ...
LFStruct2Var( LFReadMetadata(CalInfoFname), 'EstCamPosesV', 'EstCamIntrinsicsH', 'EstCamDistortionV', 'CamInfo', 'LensletGridModel', 'DecodeOptions' );
CalOptions.LFSize = LFSize;
%---Set up optimization variables---
CalOptions.IJVecToOptOver = CalOptions.LensletBorderSize+1:LFSize(1)-CalOptions.LensletBorderSize;
CalOptions.IntrinsicsToOpt = sub2ind([5,5], [1,3, 2,4, 1,3, 2,4], [1,1, 2,2, 3,3, 4,4]);
switch( lower(CalOptions.Phase) )
case 'nodistort'
CalOptions.DistortionParamsToOpt = [];
otherwise
CalOptions.DistortionParamsToOpt = 1:5;
end
if( isempty(EstCamDistortionV) && ~isempty(CalOptions.DistortionParamsToOpt) )
EstCamDistortionV(CalOptions.DistortionParamsToOpt) = 0;
end
CalOptions.PreviousCamIntrinsics = EstCamIntrinsicsH;
CalOptions.PreviousCamDistortion = EstCamDistortionV;
fprintf('\n===Calibration refinement step, optimizing:===\n');
fprintf(' Intrinsics: ');
disp(CalOptions.IntrinsicsToOpt);
if( ~isempty(CalOptions.DistortionParamsToOpt) )
fprintf(' Distortion: ');
disp(CalOptions.DistortionParamsToOpt);
end
%---Compute initial error between projected and measured corner positions---
IdealChecker = [IdealChecker; ones(1,size(IdealChecker,2))]; % homogeneous coord
%---Encode params and grab info required to build Jacobian sparsity matrix---
CalOptions.NPoses = size(EstCamPosesV,1);
[Params0, ParamsInfo, JacobSensitivity] = EncodeParams( EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CalOptions );
% Params0 = EncodeParams(EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CalOptions);
[PtPlaneDist0,JacobPattern] = FindError( Params0, CheckerObs, IdealChecker, CalOptions, ParamsInfo, JacobSensitivity );
if( numel(PtPlaneDist0) == 0 )
error('No valid grid points found -- possible grid parameter mismatch');
end
fprintf('\n Start SSE: %g m^2, RMSE: %g m\n', sum((PtPlaneDist0).^2), sqrt(mean((PtPlaneDist0).^2)));
%---Start the optimization---
ObjectiveFunc = @(Params) FindError(Params, CheckerObs, IdealChecker, CalOptions, ParamsInfo, JacobSensitivity );
OptimOptions = optimset('Display','iter', ...
'TolX', CalOptions.OptTolX, ...
'TolFun',CalOptions.OptTolFun, ...
'JacobPattern', JacobPattern, ...
'PlotFcns', @optimplotfirstorderopt, ...
'UseParallel', 'Always' );
[OptParams, ~, FinalDist] = lsqnonlin(ObjectiveFunc, Params0, [],[], OptimOptions);
%---Decode the resulting parameters and check the final error---
[EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV] = DecodeParams(OptParams, CalOptions, ParamsInfo);
fprintf(' ---Finished calibration refinement---\n');
fprintf('Estimate of camera intrinsics: \n');
disp(EstCamIntrinsicsH);
if( ~isempty( EstCamDistortionV ) )
fprintf('Estimate of camera distortion: \n');
disp(EstCamDistortionV);
end
ReprojectionError = struct( 'SSE', sum(FinalDist.^2), 'RMSE', sqrt(mean(FinalDist.^2)) );
fprintf('\n Start SSE: %g m^2, RMSE: %g m\n Finish SSE: %g m^2, RMSE: %g m\n', ...
sum((PtPlaneDist0).^2), sqrt(mean((PtPlaneDist0).^2)), ...
ReprojectionError.SSE, ReprojectionError.RMSE );
if( CalOptions.SaveResult )
TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
SaveFname = fullfile(InputPath, CalOptions.CalInfoFname);
fprintf('\nSaving to %s\n', SaveFname);
LFWriteMetadata(SaveFname, LFVar2Struct(GeneratedByInfo, LensletGridModel, EstCamIntrinsicsH, EstCamDistortionV, EstCamPosesV, CamInfo, CalOptions, DecodeOptions, ReprojectionError));
end
end
%---------------------------------------------------------------------------------------------------
function [Params0, ParamsInfo, JacobSensitivity] = EncodeParams( EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV, CalOptions )
% This makes use of FlattenStruct to reversibly flatten all params into a single array.
% It also applies the same process to a sensitivity list, to facilitate building a Jacobian
% Sparisty matrix.
% The 'P' structure contains all the parameters to encode, and the 'J' structure mirrors it exactly
% with a sensitivity list. Each entry in 'J' lists those poses that are senstitive to the
% corresponding parameter. e.g. The first estimated camera pose affects only observations made
% within the first pose, and so the sensitivity list for that parameter lists only the first pose. A
% `J' value of 0 means all poses are sensitive to that variable -- as in the case of the intrinsics,
% which affect all observations.
P.EstCamPosesV = EstCamPosesV;
J.EstCamPosesV = zeros(size(EstCamPosesV));
for( i=1:CalOptions.NPoses )
J.EstCamPosesV(i,:) = i;
end
P.IntrinParams = EstCamIntrinsicsH(CalOptions.IntrinsicsToOpt);
J.IntrinParams = zeros(size(CalOptions.IntrinsicsToOpt));
P.DistortParams = EstCamDistortionV(CalOptions.DistortionParamsToOpt);
J.DistortParams = zeros(size(CalOptions.DistortionParamsToOpt));
[Params0, ParamsInfo] = FlattenStruct(P);
JacobSensitivity = FlattenStruct(J);
end
%---------------------------------------------------------------------------------------------------
function [EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV] = DecodeParams( Params, CalOptions, ParamsInfo )
P = UnflattenStruct(Params, ParamsInfo);
EstCamPosesV = P.EstCamPosesV;
EstCamIntrinsicsH = CalOptions.PreviousCamIntrinsics;
EstCamIntrinsicsH(CalOptions.IntrinsicsToOpt) = P.IntrinParams;
EstCamDistortionV = CalOptions.PreviousCamDistortion;
EstCamDistortionV(CalOptions.DistortionParamsToOpt) = P.DistortParams;
EstCamIntrinsicsH = LFRecenterIntrinsics(EstCamIntrinsicsH, CalOptions.LFSize);
end
%---------------------------------------------------------------------------------------------------
function [Params, ParamInfo] = FlattenStruct(P)
Params = [];
ParamInfo.FieldNames = fieldnames(P);
for( i=1:length( ParamInfo.FieldNames ) )
CurFieldName = ParamInfo.FieldNames{i};
CurField = P.(CurFieldName);
ParamInfo.SizeInfo{i} = size(CurField);
Params = [Params; CurField(:)];
end
end
%---------------------------------------------------------------------------------------------------
function [P] = UnflattenStruct(Params, ParamInfo)
CurIdx = 1;
for( i=1:length( ParamInfo.FieldNames ) )
CurFieldName = ParamInfo.FieldNames{i};
CurSize = ParamInfo.SizeInfo{i};
CurField = Params(CurIdx + (0:prod(CurSize)-1));
CurIdx = CurIdx + prod(CurSize);
CurField = reshape(CurField, CurSize);
P.(CurFieldName) = CurField;
end
end
%---------------------------------------------------------------------------------------------------
function [PtPlaneDists, JacobPattern] = FindError(Params, CheckerObs, IdealChecker, CalOptions, ParamsInfo, JacobSensitivity )
%---Decode optim params---
[EstCamPosesV, EstCamIntrinsicsH, EstCamDistortionV] = DecodeParams(Params, CalOptions, ParamsInfo);
%---Tally up the total number of observations---
TotCornerObs = size( [CheckerObs{:,CalOptions.IJVecToOptOver,CalOptions.IJVecToOptOver}], 2 );
CheckCornerObs = 0;
%---Preallocate JacobPattern if it's requested---
if( nargout >= 2 )
JacobPattern = zeros(TotCornerObs, length(Params));
end
%---Preallocate point-plane distances---
PtPlaneDists = zeros(1, TotCornerObs);
%---Compute point-plane distances---
OutputIdx = 0;
for( PoseIdx = 1:CalOptions.NPoses )
%---Convert the pertinent camera pose to a homogeneous transform---
CurEstCamPoseV = squeeze(EstCamPosesV(PoseIdx, :));
CurEstCamPoseH = eye(4);
CurEstCamPoseH(1:3,1:3) = rodrigues(CurEstCamPoseV(4:6));
CurEstCamPoseH(1:3,4) = CurEstCamPoseV(1:3);
%---Iterate through the corners---
for( TIdx = CalOptions.IJVecToOptOver )
for( SIdx = CalOptions.IJVecToOptOver )
CurCheckerObs = CheckerObs{PoseIdx, TIdx,SIdx};
NCornerObs = size(CurCheckerObs,2);
if( NCornerObs ~= prod(CalOptions.ExpectedCheckerSize) )
continue; % this implementation skips incomplete observations
end
CheckCornerObs = CheckCornerObs + NCornerObs;
%---Assemble observed corner positions into complete 4D [i,j,k,l] indices---
CurCheckerObs_Idx = [repmat([SIdx;TIdx], 1, NCornerObs); CurCheckerObs; ones(1, NCornerObs)];
%---Transform ideal 3D corner coords into camera's reference frame---
IdealChecker_CamFrame = CurEstCamPoseH * IdealChecker;
IdealChecker_CamFrame = IdealChecker_CamFrame(1:3,:); % won't be needing homogeneous points
%---Project observed corner indices to [s,t,u,v] rays---
CurCheckerObs_Ray = EstCamIntrinsicsH * CurCheckerObs_Idx;
%---Apply direction-dependent distortion model---
if( ~isempty(EstCamDistortionV) && any(EstCamDistortionV(:)~=0))
k1 = EstCamDistortionV(1);
k2 = EstCamDistortionV(2);
k3 = EstCamDistortionV(3);
b1dir = EstCamDistortionV(4);
b2dir = EstCamDistortionV(5);
Direction = CurCheckerObs_Ray(3:4,:);
Direction = bsxfun(@minus, Direction, [b1dir;b2dir]);
DirectionR2 = sum(Direction.^2);
Direction = Direction .* repmat((1 + k1.*DirectionR2 + k2.*DirectionR2.^2 + k3.*DirectionR2.^4),2,1);
Direction = bsxfun(@plus, Direction, [b1dir;b2dir]);
CurCheckerObs_Ray(3:4,:) = Direction;
end
%---Find 3D point-ray distance---
STPlaneIntersect = [CurCheckerObs_Ray(1:2,:); zeros(1,NCornerObs)];
RayDir = [CurCheckerObs_Ray(3:4,:); ones(1,NCornerObs)];
CurDist3D = LFFind3DPtRayDist( STPlaneIntersect, RayDir, IdealChecker_CamFrame );
PtPlaneDists(OutputIdx + (1:NCornerObs)) = CurDist3D;
if( nargout >=2 )
% Build the Jacobian pattern. First we enumerate those observations related to
% the current pose, then find all parameters to which those observations are
% sensitive. This relies on the JacobSensitivity list constructed by the
% FlattenStruct function.
CurObservationList = OutputIdx + (1:NCornerObs);
CurSensitivityList = (JacobSensitivity==PoseIdx | JacobSensitivity==0);
JacobPattern(CurObservationList, CurSensitivityList) = 1;
end
OutputIdx = OutputIdx + NCornerObs;
end
end
end
%---Check that the expected number of observations have gone by---
if( CheckCornerObs ~= TotCornerObs )
error(['Mismatch between expected (%d) and observed (%d) number of corners' ...
' -- possibly caused by a grid parameter mismatch'], TotCornerObs, CheckCornerObs);
end
end
%---Compute distances from 3D rays to a 3D points---
function [Dist] = LFFind3DPtRayDist( PtOnRay, RayDir, Pt3D )
RayDir = RayDir ./ repmat(sqrt(sum(RayDir.^2)), 3,1); % normalize ray
Pt3D = Pt3D - PtOnRay; % Vector to point
PD1 = dot(Pt3D, RayDir);
PD1 = repmat(PD1,3,1).*RayDir; % Project point vec onto ray vec
Pt3D = Pt3D - PD1;
Dist = sqrt(sum(Pt3D.^2, 1)); % Distance from point to projected point
end
|
github
|
Vincentqyw/light-field-TB-master
|
LFNormalizedFreqAxis.m
|
.m
|
light-field-TB-master/LFToolbox0.4/SupportFunctions/LFNormalizedFreqAxis.m
| 579 |
utf_8
|
02656a40ea9705a7d443208d9349a19e
|
% LFNormalizedFreqAxis - Helper function to construct a frequency axis
%
% Output range is from -0.5 to 0.5. This is designed so that the zero frequency matches the fftshifted output of the
% fft algorithm.
% Part of LF Toolbox v0.4 released 12-Feb-2015
% Copyright (c) 2013-2015 Donald G. Dansereau
function f = LFNormalizedFreqAxis( NSamps, Precision )
Precision = LFDefaultVal( 'Precision', 'double' );
if( NSamps == 1 )
f = 0;
elseif( mod(NSamps,2) )
f = [-(NSamps-1)/2:(NSamps-1)/2]/(NSamps-1);
else
f = [-NSamps/2:(NSamps/2-1)]/NSamps;
end
f = cast(f, Precision);
|
github
|
shivamsaboo17/MyMachine-master
|
submit.m
|
.m
|
MyMachine-master/Coursehub/Coursera_IntroToML_AndrewNG/AndrewNG/ex1/submit.m
| 1,876 |
utf_8
|
8d1c467b830a89c187c05b121cb8fbfd
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'linear-regression';
conf.itemName = 'Linear Regression with Multiple Variables';
conf.partArrays = { ...
{ ...
'1', ...
{ 'warmUpExercise.m' }, ...
'Warm-up Exercise', ...
}, ...
{ ...
'2', ...
{ 'computeCost.m' }, ...
'Computing Cost (for One Variable)', ...
}, ...
{ ...
'3', ...
{ 'gradientDescent.m' }, ...
'Gradient Descent (for One Variable)', ...
}, ...
{ ...
'4', ...
{ 'featureNormalize.m' }, ...
'Feature Normalization', ...
}, ...
{ ...
'5', ...
{ 'computeCostMulti.m' }, ...
'Computing Cost (for Multiple Variables)', ...
}, ...
{ ...
'6', ...
{ 'gradientDescentMulti.m' }, ...
'Gradient Descent (for Multiple Variables)', ...
}, ...
{ ...
'7', ...
{ 'normalEqn.m' }, ...
'Normal Equations', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId)
% Random Test Cases
X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];
Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));
X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];
Y2 = Y1.^0.5 + Y1;
if partId == '1'
out = sprintf('%0.5f ', warmUpExercise());
elseif partId == '2'
out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));
elseif partId == '3'
out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10));
elseif partId == '4'
out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));
elseif partId == '5'
out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]'));
elseif partId == '6'
out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10));
elseif partId == '7'
out = sprintf('%0.5f ', normalEqn(X2, Y2));
end
end
|
github
|
shivamsaboo17/MyMachine-master
|
submitWithConfiguration.m
|
.m
|
MyMachine-master/Coursehub/Coursera_IntroToML_AndrewNG/AndrewNG/ex1/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
shivamsaboo17/MyMachine-master
|
savejson.m
|
.m
|
MyMachine-master/Coursehub/Coursera_IntroToML_AndrewNG/AndrewNG/ex1/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
shivamsaboo17/MyMachine-master
|
loadjson.m
|
.m
|
MyMachine-master/Coursehub/Coursera_IntroToML_AndrewNG/AndrewNG/ex1/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
shivamsaboo17/MyMachine-master
|
loadubjson.m
|
.m
|
MyMachine-master/Coursehub/Coursera_IntroToML_AndrewNG/AndrewNG/ex1/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
shivamsaboo17/MyMachine-master
|
saveubjson.m
|
.m
|
MyMachine-master/Coursehub/Coursera_IntroToML_AndrewNG/AndrewNG/ex1/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
Macquarie-MEG-Research/coreg-master
|
coreg_yokogawa_icp_paul.m
|
.m
|
coreg-master/coreg_yokogawa_icp_paul.m
| 22,340 |
utf_8
|
39b893f0f50b02e736edf9158bb0510b
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% coreg_yokogawa_icp is a function to coregister a structural MRI with MEG data
% and associated headshape information
%
% Written by Robert Seymour Oct 2017 (some subfunctions written by Paul
% Sowman)
%
% INPUTS:
% - dir_name = directory name for the output of your coreg
% - confile = full path to the con file
% - mrkfile = full path to the mrk file
% - mri_file = full path to the NIFTI structural MRI file
% - hspfile = full path to the hsp (polhemus headshape) file
% - elpfile = full path to the elp file
% - hsp_points = number of points for downsampling the headshape (try 100-200)
% - scalpthreshold = threshold for scalp extraction (try 0.05 if unsure)
%
% OUTPUTS:
% - grad_trans = correctly aligned sensor layout
% - headshape_downsampled = downsampled headshape (original variable name I know)
% - mri_realigned = the mri realigned based on fiducial points
% - trans_matrix = transformation matrix for accurate coregistration
% - headmodel_singleshell = coregistered singleshell headmodel
%
% THIS IS A WORK IN PROGRESS FUNCTION - any updates or suggestions would be
% much appreciated
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function coreg_yokogawa_icp(dir_name,confile,mrkfile,mri_file,hspfile,elpfile,hsp_points,scalpthreshold)
cd(dir_name); disp('CDd to the right place');
% Get Polhemus Points
[shape] = parsePolhemus(elpfile,hspfile);
% Read the grads from the con file
grad_con = ft_read_sens(confile); %in cm, load grads
% Read the mrk file
mrk = ft_read_headshape(mrkfile,'format','yokogawa_mrk');
markers = mrk.fid.pos([2 3 1 4 5],:);%reorder mrk to match order in shape
[R,T,Yf,Err] = rot3dfit(markers,shape.fid.pnt(4:end,:));%calc rotation transform
meg2head_transm = [[R;T]'; 0 0 0 1];%reorganise and make 4*4 transformation matrix
rot180mat = rotate_about_z(180);
% Transform sensors based on the MRKfile
grad_trans = ft_transform_geometry_PFS_hacked(meg2head_transm,grad_con); %Use my hacked version of the ft function - accuracy checking removed not sure if this is good or not
grad_trans.fid = shape; %add in the head information
grad_trans = ft_transform_geometry(rot180mat,grad_trans);
%save grad_trans grad_trans
% Get headshape downsampled to 100 points with facial info preserved
headshape_downsampled = downsample_headshape(hspfile,hsp_points,grad_trans);
headshape_downsampled = ft_transform_geometry(rot180mat,headshape_downsampled);
%save headshape_downsampled headshape_downsampled
% Load in MRI
mri_orig = ft_read_mri(mri_file); % in mm, read in mri from DICOM
mri_orig = ft_convert_units(mri_orig,'cm'); mri_orig.coordsys = 'neuromag';
% Give rough estimate of fiducial points
cfg = [];
cfg.method = 'interactive';
cfg.viewmode = 'ortho';
cfg.coordsys = 'neuromag';
[mri_realigned] = ft_volumerealign(cfg, mri_orig);
save mri_realigned mri_realigned
% check that the MRI is consistent after realignment
ft_determine_coordsys(mri_realigned, 'interactive', 'no');
hold on; % add the subsequent objects to the figure
drawnow; % workaround to prevent some MATLAB versions (2012b and 2014b) from crashing
ft_plot_headshape(headshape_downsampled);
%% Extract Scalp Surface
cfg = [];
cfg.output = 'scalp';
cfg.scalpsmooth = 5;
cfg.scalpthreshold = scalpthreshold;
scalp = ft_volumesegment(cfg, mri_realigned);
%% Create mesh out of scalp surface
cfg = [];
cfg.method = 'projectmesh';
cfg.numvertices = 90000;
mesh = ft_prepare_mesh(cfg,scalp);
mesh = ft_convert_units(mesh,'cm');
% Flip the mesh around (improves coreg)
%mesh.pos(:,2) = mesh.pos(:,2).*-1; % gonna try flipping the other stuff
%earlier
%% Create Figure for Quality Checking
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on; drawnow;
view(90,0);
title('If this looks weird you might want to adjust the cfg.scalpthreshold value');
print('mesh_quality','-dpdf');
%% Create a figure to check the scalp mesh and headshape points
figure;ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
ft_plot_headshape(headshape_downsampled); drawnow;
%% Perform ICP using mesh and headshape information
numiter = 50;
disp('Performing ICP fit with 50 iterations');
[R, t, err, dummy, info] = icp(mesh.pos', headshape_downsampled.pos', numiter, 'Minimize', 'plane', 'Extrapolation', true, 'WorstRejection', 0.05);
%% Create figure to display how the ICP algorithm reduces error
%figure;plot(1:1:49,err);
%% Create transformation matrix
%trans_matrix = inv([real(R) real(t);0 0 0 1]);% gonna go the other way
trans_matrix = [real(R) real(t);0 0 0 1];
save trans_matrix trans_matrix
%% Create figure to assess accuracy of coregistration
mesh_spare = mesh;
%mesh_spare.pos = ft_warp_apply(trans_matrix, mesh_spare.pos);
grad_trans=ft_transform_geometry(trans_matrix,grad_trans);
headshape_downsampled=ft_transform_geometry(trans_matrix,headshape_downsampled);
save grad_trans grad_trans
save headshape_downsampled headshape_downsampled
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('Error of ICP fit = %d' , err));
print('mesh_quality','-dpdf');
%% Segment
cfg = [];
cfg.output = {'brain' 'scalp' 'skull'};
mri_segmented = ft_volumesegment(cfg, mri_realigned);
%% Create singleshell headmodel
cfg = [];
cfg.method = 'singleshell';
headmodel_singleshell = ft_prepare_headmodel(cfg, mri_segmented); % in cm, create headmodel
% Flip headmodel around
%headmodel_singleshell.bnd.pos(:,2) = headmodel_singleshell.bnd.pos(:,2).*-1;
% Apply transformation matrix
%headmodel_singleshell.bnd.pos = ft_warp_apply(trans_matrix,headmodel_singleshell.bnd.pos);
%Can we flip and warp the MRI here too so that it's in same orientation?
figure;ft_plot_headshape(headshape_downsampled) %plot headshape
ft_plot_sens(grad_trans, 'style', 'k*')
ft_plot_vol(headmodel_singleshell, 'facecolor', 'cortex', 'edgecolor', 'none');alpha 1; camlight
view([90,0]); title('After Coreg');
print('headmodel_quality','-dpdf');
save headmodel_singleshell headmodel_singleshell
% %plot original headshape points on scalp mesh - deflate scalp a little bit
% %first
% figure;
% mesh_scalp_defl = mesh;
% mesh_scalp_defl.pos = 0.9 * mesh_scalp_defl.pos;
%
% figure
% ft_plot_mesh(mesh_scalp_defl, 'edgecolor', 'none', 'facecolor', 'skin')
% material dull
% camlight
% lighting phong
% hold on
% ft_plot_headshape(grad_trans.fid)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUBFUNCTIONS
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [shape] = parsePolhemus(elpfile,hspfile)
fid1 = fopen(elpfile);
C = fscanf(fid1,'%c');
fclose(fid1);
E = regexprep(C,'\r','xx');
E = regexprep(E,'\t','yy');
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
sensornamesi = strfind(E,'%N');
fiducialsstarti = strfind(E,'%F');
lastfidendi = strfind(E(fiducialsstarti(3):fiducialsstarti(length(fiducialsstarti))+100),'xx');
fiducialsendi = fiducialsstarti(1)+strfind(E(fiducialsstarti(1):fiducialsstarti(length(fiducialsstarti))+lastfidendi(1)),'xx');
NASION = E(fiducialsstarti(1)+4:fiducialsendi(1)-2);
NASION = regexprep(NASION,'yy','\t');
NASION = str2num(NASION);
LPA = E(fiducialsstarti(2)+4:fiducialsendi(2)-2);
LPA = regexprep(LPA,'yy','\t');
LPA = str2num(LPA);
RPA = E(fiducialsstarti(3)+4:fiducialsendi(3)-2);
RPA = regexprep(RPA,'yy','\t');
RPA = str2num(RPA);
LPAredstarti = strfind(E,'LPAred');
LPAredendi = strfind(E(LPAredstarti(1):LPAredstarti(length(LPAredstarti))+45),'xx');
LPAred = E(LPAredstarti(1)+11:LPAredstarti(1)+LPAredendi(2)-2);
LPAred = regexprep(LPAred,'yy','\t');
LPAred = str2num(LPAred);
RPAyelstarti = strfind(E,'RPAyel');
RPAyelendi = strfind(E(RPAyelstarti(1):RPAyelstarti(length(RPAyelstarti))+45),'xx');
RPAyel = E(RPAyelstarti(1)+11:RPAyelstarti(1)+RPAyelendi(2)-2);
RPAyel = regexprep(RPAyel,'yy','\t');
RPAyel = str2num(RPAyel);
PFbluestarti = strfind(E,'PFblue');
PFblueendi = strfind(E(PFbluestarti(1):PFbluestarti(length(PFbluestarti))+45),'xx');
PFblue = E(PFbluestarti(1)+11:PFbluestarti(1)+PFblueendi(2)-2);
PFblue = regexprep(PFblue,'yy','\t');
PFblue = str2num(PFblue);
LPFwhstarti = strfind(E,'LPFwh');
LPFwhendi = strfind(E(LPFwhstarti(1):LPFwhstarti(length(LPFwhstarti))+45),'xx');
LPFwh = E(LPFwhstarti(1)+11:LPFwhstarti(1)+LPFwhendi(2)-2);
LPFwh = regexprep(LPFwh,'yy','\t');
LPFwh = str2num(LPFwh);
RPFblackstarti = strfind(E,'RPFblack');
RPFblackendi = strfind(E(RPFblackstarti(1):end),'xx');
RPFblack = E(RPFblackstarti(1)+11:RPFblackstarti(1)+RPFblackendi(2)-2);
RPFblack = regexprep(RPFblack,'yy','\t');
RPFblack = str2num(RPFblack);
allfids = [NASION;LPA;RPA;LPAred;RPAyel;PFblue;LPFwh;RPFblack];
fidslabels = {'NASION';'LPA';'RPA';'LPAred';'RPAyel';'PFblue';'LPFwh';'RPFblack'};
fid2 = fopen(hspfile);
C = fscanf(fid2,'%c');
fclose(fid2);
E = regexprep(C,'\r','xx'); %replace returns with "xx"
E = regexprep(E,'\t','yy'); %replace tabs with "yy"
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
headshapestarti = strfind(E,'position of digitized points');
headshapestartii = strfind(E(headshapestarti(1):end),'xx');
headshape = E(headshapestarti(1)+headshapestartii(2)+2:end);
headshape = regexprep(headshape,'yy','\t');
headshape = regexprep(headshape,'xx','');
headshape = str2num(headshape);
shape.pnt = headshape;
shape.fid.pnt = allfids;
shape.fid.label = fidslabels;
%convert to BESA style coordinates so can use the .pos file or sensor
%config from .con
shape.pnt = cat(2,fliplr(shape.pnt(:,1:2)),shape.pnt(:,3)).*1000;
%shape.pnt = shape.pnt(1:length(shape.pnt)-15,:); % get rid of nose points may want to alter or comment this depending on your digitisation
%shape.pnt = shape.pnt*1000;
neg = shape.pnt(:,2)*-1;
shape.pnt(:,2) = neg;
shape.fid.pnt = cat(2,fliplr(shape.fid.pnt(:,1:2)),shape.fid.pnt(:,3)).*1000;
%shape.fid.pnt = shape.fid.pnt*1000;
neg2 = shape.fid.pnt(:,2)*-1;
shape.fid.pnt(:,2) = neg2;
shape.unit = 'mm';
shape = ft_convert_units(shape,'cm');
new_name2 = ['shape.mat'];
save (new_name2,'shape');
end
function [R,T,Yf,Err] = rot3dfit(X,Y)
%ROT3DFIT Determine least-square rigid rotation and translation.
% [R,T,Yf] = ROT3DFIT(X,Y) permforms a least-square fit for the
% linear form
%
% Y = X*R + T
%
% where R is a 3 x 3 orthogonal rotation matrix, T is a 1 x 3
% translation vector, and X and Y are 3D points sets defined as
% N x 3 matrices. Yf is the best-fit matrix.
%
% See also SVD, NORM.
%
% rot3dfit: Frank Evans, NHLBI/NIH, 30 November 2001
%
% ROT3DFIT uses the method described by K. S. Arun, T. S. Huang,and
% S. D. Blostein, "Least-Squares Fitting of Two 3-D Point Sets",
% IEEE Transactions on Pattern Analysis and Machine Intelligence,
% PAMI-9(5): 698 - 700, 1987.
%
% A better theoretical development is found in B. K. P. Horn,
% H. M. Hilden, and S. Negahdaripour, "Closed-form solution of
% absolute orientation using orthonormal matrices", Journal of the
% Optical Society of America A, 5(7): 1127 - 1135, 1988.
%
% Special cases, e.g. colinear and coplanar points, are not
% implemented.
%error(nargchk(2,2,nargin));
narginchk(2,2); %PFS Change to update
if size(X,2) ~= 3, error('X must be N x 3'); end;
if size(Y,2) ~= 3, error('Y must be N x 3'); end;
if size(X,1) ~= size(Y,1), error('X and Y must be the same size'); end;
% mean correct
Xm = mean(X,1); X1 = X - ones(size(X,1),1)*Xm;
Ym = mean(Y,1); Y1 = Y - ones(size(Y,1),1)*Ym;
% calculate best rotation using algorithm 12.4.1 from
% G. H. Golub and C. F. van Loan, "Matrix Computations"
% 2nd Edition, Baltimore: Johns Hopkins, 1989, p. 582.
XtY = (X1')*Y1;
[U,S,V] = svd(XtY);
R = U*(V');
% solve for the translation vector
T = Ym - Xm*R;
% calculate fit points
Yf = X*R + ones(size(X,1),1)*T;
% calculate the error
dY = Y - Yf;
Err = norm(dY,'fro'); % must use Frobenius norm
end
function [output] = ft_transform_geometry_PFS_hacked(transform, input)
% FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to
% a structure with geometric information, for example a volume conduction model
% for the head, gradiometer of electrode structure containing EEG or MEG
% sensor positions and MEG coil orientations, a head shape or a source model.
%
% The units in which the transformation matrix is expressed are assumed to
% be the same units as the units in which the geometric object is
% expressed. Depending on the input object, the homogeneous transformation
% matrix should be limited to a rigid-body translation plus rotation
% (MEG-gradiometer array), or to a rigid-body translation plus rotation
% plus a global rescaling (volume conductor geometry).
%
% Use as
% output = ft_transform_geometry(transform, input)
%
% See also FT_WARP_APPLY, FT_HEADCOORDINATES
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_transform_geometry.m$
% flg rescaling check
allowscaling = ~ft_senstype(input, 'meg');
% determine the rotation matrix
rotation = eye(4);
rotation(1:3,1:3) = transform(1:3,1:3);
if any(abs(transform(4,:)-[0 0 0 1])>100*eps)
error('invalid transformation matrix');
end
%%### get rid of this accuracy checking below as some of the transformation
%%matricies will be a bit hairy###
if ~allowscaling
% allow for some numerical imprecision
%if abs(det(rotation)-1)>1e-6%100*eps
%if abs(det(rotation)-1)>100*eps % allow for some numerical imprecision
%error('only a rigid body transformation without rescaling is allowed');
%end
end
if allowscaling
% FIXME build in a check for uniform rescaling probably do svd or so
% FIXME insert check for nonuniform scaling, should give an error
end
tfields = {'pos' 'pnt' 'o' 'coilpos' 'chanpos' 'chanposold' 'chanposorg' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation
rfields = {'ori' 'nrm' 'coilori' 'chanori' 'chanoriold' 'chanoriorg'}; % only apply rotation
mfields = {'transform'}; % plain matrix multiplication
recfields = {'fid' 'bnd' 'orig'}; % recurse into these fields
% the field 'r' is not included here, because it applies to a volume
% conductor model, and scaling is not allowed, so r will not change.
fnames = fieldnames(input);
for k = 1:numel(fnames)
if ~isempty(input.(fnames{k}))
if any(strcmp(fnames{k}, tfields))
input.(fnames{k}) = apply(transform, input.(fnames{k}));
elseif any(strcmp(fnames{k}, rfields))
input.(fnames{k}) = apply(rotation, input.(fnames{k}));
elseif any(strcmp(fnames{k}, mfields))
input.(fnames{k}) = transform*input.(fnames{k});
elseif any(strcmp(fnames{k}, recfields))
for j = 1:numel(input.(fnames{k}))
input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j));
end
else
% do nothing
end
end
end
output = input;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that applies the homogeneous transformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [new] = apply(transform, old)
old(:,4) = 1;
new = old * transform';
new = new(:,1:3);
end
function [headshape_downsampled] = downsample_headshape(path_to_headshape,numvertices,sensors)
% Get headshape
headshape = ft_read_headshape(path_to_headshape);
% Convert to cm
headshape = ft_convert_units(headshape,'cm');
% Convert to BESA co-ordinates
headshape.pos = cat(2,fliplr(headshape.pos(:,1:2)),headshape.pos(:,3));
headshape.pos(:,2) = headshape.pos(:,2).*-1;
% Get indices of facial points (up to 4cm above nasion)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Is 4cm the correct distance?
% Possibly different for child system?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
count_facialpoints = find(headshape.pos(:,3)<4);
if isempty(count_facialpoints)
disp('CANNOT FIND ANY FACIAL POINTS - COREG BY ICP MAY BE INACCURATE');
else
facialpoints = headshape.pos(count_facialpoints,:,:);
rrr = 1:4:length(facialpoints);
facialpoints = facialpoints(rrr,:); clear rrr;
end
% Remove facial points for now
headshape.pos(count_facialpoints,:) = [];
% Create mesh out of headshape downsampled to x points specified in the
% function call
cfg.numvertices = numvertices;
cfg.method = 'headshape';
cfg.headshape = headshape.pos;
mesh = ft_prepare_mesh(cfg, headshape);
% Replace the headshape info with the mesh points
headshape.pos = mesh.pos;
% Create figure for quality checking
figure; subplot(2,2,1);ft_plot_mesh(mesh); hold on;
title('Downsampled Mesh');
view(0,0);
subplot(2,2,2);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 1');
view(0,0);
subplot(2,2,3);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 2');
view(90,0);
subplot(2,2,4);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 3');
view(180,0);
print('headshape_quality','-dpdf');
% Add the facial info back in
headshape.pos = vertcat(headshape.pos,facialpoints);
% Add in names of the fiducials from the sensor
headshape.fid.label = {'NASION','LPA','RPA'};
% Convert fiducial points to BESA
headshape.fid.pos = cat(2,fliplr(headshape.fid.pos(:,1:2)),headshape.fid.pos(:,3));
headshape.fid.pos(:,2) = headshape.fid.pos(:,2).*-1;
% Plot for quality checking
figure;ft_plot_sens(sensors) %plot channel position : between the 1st and 2nd coils
ft_plot_headshape(headshape) %plot headshape
view(0,0);
print('headshape_quality2','-dpdf');
% Export filename
headshape_downsampled = headshape;
end
end
|
github
|
Macquarie-MEG-Research/coreg-master
|
coreg_yokogawa_icp_adjust_weights.m
|
.m
|
coreg-master/coreg_yokogawa_icp_adjust_weights.m
| 26,869 |
utf_8
|
3e9181b9d9937fa72a65e09d073ee213
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% coreg_yokogawa_icp_adjust_weights is a function to coregister a structural
% MRI with MEG data and associated headshape information
%
% Written by Robert Seymour Oct 2017 - July 2018 (some subfunctions
% contributed by Paul Sowman)
%
% INPUTS:
% - dir_name = directory name for the output of your coreg
% - confile = full path to the con file
% - mrkfile = full path to the mrk file
% - mri_file = full path to the NIFTI structural MRI file
% - hspfile = full path to the hsp (polhemus headshape) file
% - elpfile = full path to the elp file
% - hsp_points = number of points for downsampling the headshape (try 100-200)
% - scalpthreshold = threshold for scalp extraction (try 0.05 if unsure)
%
% VARIABLE INPUTS (if using please specify all):
% - do_vids = save videos to file. Requires CaptureFigVid.
% - weight_number = how strongly do you want to weight the facial points?
% - bad_coil = is there a bad coil to take out?
%
% EXAMPLE FUNCTION CALL:
% coreg_yokogawa_icp_adjust_weights(dir_name,confile,mrkfile,mri_file,...
% hspfile,elpfile,hsp_points, scalpthreshold,'yes',0.8,'')
%
% OUTPUTS:
% - grad_trans = correctly aligned sensor layout
% - headshape_downsampled = downsampled headshape (original variable name I know)
% - mri_realigned = the mri realigned based on fiducial points
% - trans_matrix = transformation matrix for accurate coregistration
% - mri_realigned2 = the coregistered mri based on ICP algorithm
% - headmodel_singleshell = coregistered singleshell headmodel
%
% THIS IS A WORK IN PROGRESS FUNCTION - any updates or suggestions would be
% much appreciated
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function coreg_yokogawa_icp_adjust_weights(dir_name,confile,mrkfile,mri_file,hspfile,elpfile,hsp_points,scalpthreshold,varargin)
if isempty(varargin)
do_vids = 'no';
weight_number = 0.1;
bad_coil = '';
else
do_vids = varargin{1};
weight_number = 1./varargin{2};
bad_coil = varargin{3}
end
cd(dir_name); disp('CDd to the right place');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Load initial variables & check the input of the function
% Get Polhemus Points
disp('Reading elp and headshape data');
[shape] = parsePolhemus(elpfile,hspfile);
shape = ft_convert_units(shape,'cm');
% Read the grads from the con file
disp('Reading sensor data from con file');
grad_con = ft_read_sens(confile); %load grads
grad_con = ft_convert_units(grad_con,'cm'); %in cm
% Read mrk_file
disp('Reading the mrk file');
mrk = ft_read_headshape(mrkfile,'format','yokogawa_mrk');
mrk = ft_convert_units(mrk,'cm'); %in cm
% Get headshape downsampled to specified no. of points
% with facial info preserved
fprintf('Downsampling headshape information to %d points whilst preserving facial information\n'...
,hsp_points);
headshape_downsampled = downsample_headshape(hspfile,hsp_points);
% Load in MRI
disp('Reading the MRI file');
mri_orig = ft_read_mri(mri_file); % in mm, read in mri from DICOM
mri_orig = ft_convert_units(mri_orig,'cm');
mri_orig.coordsys = 'neuromag';
% MRI...
% Give rough estimate of fiducial points
cfg = [];
cfg.method = 'interactive';
cfg.viewmode = 'ortho';
cfg.coordsys = 'bti';
[mri_realigned] = ft_volumerealign(cfg, mri_orig);
disp('Saving the first realigned MRI');
%save mri_realigned mri_realigned
% check that the MRI is consistent after realignment
ft_determine_coordsys(mri_realigned, 'interactive', 'no');
hold on; % add the subsequent objects to the figure
drawnow; % workaround to prevent some MATLAB versions (2012b and 2014b) from crashing
ft_plot_headshape(headshape_downsampled);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
% If there is no bad marker perform coreg normally
if isempty(bad_coil)
markers = mrk.fid.pos([2 3 1 4 5],:);%reorder mrk to match order in shape
[R,T,Yf,Err] = rot3dfit(markers,shape.fid.pnt(4:end,:));%calc rotation transform
meg2head_transm = [[R;T]'; 0 0 0 1];%reorganise and make 4*4 transformation matrix
grad_trans = ft_transform_geometry_PFS_hacked(meg2head_transm,grad_con); %Use my hacked version of the ft function - accuracy checking removed not sure if this is good or not
grad_trans.fid = shape; %add in the head information
save grad_trans grad_trans
% Else if there is a bad marker take out this info and perform coreg
else
fprintf(''); disp('TAKING OUT BAD MARKER');
% Identify the bad coil
badcoilpos = find(ismember(shape.fid.label,bad_coil));
% Take away the bad marker
marker_order = [2 3 1 4 5];
markers = mrk.fid.pos(marker_order,:);%reorder mrk to match order in shape
% Now take out the bad marker when you realign
markers(badcoilpos-3,:) = [];
fids_2_use = shape.fid.pnt(4:end,:); fids_2_use(badcoilpos-3,:) = [];
[R,T,Yf,Err] = rot3dfit(markers,fids_2_use);%calc rotation transform
meg2head_transm = [[R;T]'; 0 0 0 1];%reorganise and make 4*4 transformation matrix
grad_trans = ft_transform_geometry_PFS_hacked(meg2head_transm,grad_con); %Use my hacked version of the ft function - accuracy checking removed not sure if this is good or not
grad_trans.fid = shape; %add in the head information
save grad_trans grad_trans
end
%% Extract Scalp Surface
cfg = [];
cfg.output = 'scalp';
cfg.scalpsmooth = 5;
cfg.scalpthreshold = scalpthreshold;
scalp = ft_volumesegment(cfg, mri_realigned);
%% Create mesh out of scalp surface
cfg = [];
cfg.method = 'isosurface';
cfg.numvertices = 10000;
mesh = ft_prepare_mesh(cfg,scalp);
mesh = ft_convert_units(mesh,'cm');
%% Create Figure for Quality Checking
if strcmp(do_vids,'yes')
try
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull
hold on; drawnow; view(0,0);
ft_plot_headshape(headshape_downsampled); drawnow;
OptionZ.FrameRate=15;OptionZ.Duration=5.5;OptionZ.Periodic=true;
CaptureFigVid([0,0; 360,0], 'mesh_quality',OptionZ)
catch
disp('You need CaptureFigVid in your MATLAB path. Download at https://goo.gl/Qr7GXb');
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull
hold on; drawnow;
ft_plot_headshape(headshape_downsampled); drawnow;
view(0,0);print('mesh_quality','-dpng');
end
else
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull
hold on; drawnow;
view(90,0);
ft_plot_headshape(headshape_downsampled); drawnow;
title('If this looks weird you might want to adjust the cfg.scalpthreshold value');
print('mesh_quality','-dpng');
end
%% Perform ICP using mesh and headshape information
numiter = 50;
disp('Performing ICP fit with 50 iterations\n');
% Weight the facial points x10 times higher than the head points
count_facialpoints2 = find(headshape_downsampled.pos(:,3)<3); x = 1;
% If there are no facial points ignore the weighting
if isempty(count_facialpoints2)
w = ones(size(headshape_downsampled.pos,1),1).*1;
weights = @(x)assignweights(x,w);
disp('NOT Applying Weighting\n');
% But if there are facial points apply weighting using weight_number
else
w = ones(size(headshape_downsampled.pos,1),1).*weight_number;
w(count_facialpoints2) = 1;
weights = @(x)assignweights(x,w);
fprintf('Applying Weighting of %d \n',weight_number);
end
% Now try ICP with weights
[R, t, err] = icp(mesh.pos', headshape_downsampled.pos', numiter, 'Minimize', 'plane', 'Extrapolation', true, 'Weight', weights, 'WorstRejection', 0.05);
%% Create figure to display how the ICP algorithm reduces error
clear plot;
figure; plot([1:1:51]',err,'LineWidth',8);
ylabel('Error'); xlabel('Iteration');
title('Error*Iteration');
set(gca,'FontSize',25);
%% Create transformation matrix
trans_matrix = inv([real(R) real(t);0 0 0 1]);
save trans_matrix trans_matrix
%% Create figure to assess accuracy of coregistration
mesh_spare = mesh;
mesh_spare.pos = ft_warp_apply(trans_matrix, mesh_spare.pos);
c = datestr(clock); %time and date
if strcmp(do_vids,'yes')
try
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
OptionZ.FrameRate=15;OptionZ.Duration=5.5;OptionZ.Periodic=true;
CaptureFigVid([0,0; 360,0], 'ICP_quality',OptionZ)
catch
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
print('ICP_quality','-dpng');
disp('You need CaptureFigVid in your MATLAB path. Download at https://goo.gl/Qr7GXb');
end
else
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
clear c; print('ICP_quality','-dpng');
end
%% Apply transform to the MRI
mri_realigned2 = ft_transform_geometry(trans_matrix,mri_realigned);
save mri_realigned2 mri_realigned2
% check that the MRI is consistent after realignment
ft_determine_coordsys(mri_realigned2, 'interactive', 'no');
hold on; % add the subsequent objects to the figure
drawnow; % workaround to prevent some MATLAB versions (2012b and 2014b) from crashing
ft_plot_headshape(headshape_downsampled);
%% Segment
cfg = [];
cfg.output = 'brain';
mri_segmented = ft_volumesegment(cfg, mri_realigned2);
%% Create singleshell headmodel
cfg = [];
cfg.method='singleshell';
headmodel_singleshell = ft_prepare_headmodel(cfg, mri_segmented); % in cm, create headmodel
% Flip headmodel around
%headmodel_singleshell.bnd.pos(:,2) = headmodel_singleshell.bnd.pos(:,2).*-1;
% Apply transformation matrix
%headmodel_singleshell.bnd.pos = ft_warp_apply(trans_matrix,headmodel_singleshell.bnd.pos);
figure;ft_plot_headshape(headshape_downsampled) %plot headshape
ft_plot_sens(grad_trans, 'style', 'k*')
ft_plot_vol(headmodel_singleshell, 'facecolor', 'cortex', 'edgecolor', 'cortex'); alpha(1.0); hold on;
ft_plot_mesh(mesh_spare,'facecolor','skin'); alpha(0.2);
camlight left; camlight right; material dull; hold on;
view([90,0]); title('After Coreg');
print('headmodel_quality','-dpdf');
save headmodel_singleshell headmodel_singleshell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUBFUNCTIONS
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [shape] = parsePolhemus(elpfile,hspfile)
fid1 = fopen(elpfile);
C = fscanf(fid1,'%c');
fclose(fid1);
E = regexprep(C,'\r','xx');
E = regexprep(E,'\t','yy');
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
sensornamesi = strfind(E,'%N');
fiducialsstarti = strfind(E,'%F');
lastfidendi = strfind(E(fiducialsstarti(3):fiducialsstarti(length(fiducialsstarti))+100),'xx');
fiducialsendi = fiducialsstarti(1)+strfind(E(fiducialsstarti(1):fiducialsstarti(length(fiducialsstarti))+lastfidendi(1)),'xx');
NASION = E(fiducialsstarti(1)+4:fiducialsendi(1)-2);
NASION = regexprep(NASION,'yy','\t');
NASION = str2num(NASION);
LPA = E(fiducialsstarti(2)+4:fiducialsendi(2)-2);
LPA = regexprep(LPA,'yy','\t');
LPA = str2num(LPA);
RPA = E(fiducialsstarti(3)+4:fiducialsendi(3)-2);
RPA = regexprep(RPA,'yy','\t');
RPA = str2num(RPA);
LPAredstarti = strfind(E,'LPAred');
LPAredendi = strfind(E(LPAredstarti(1):LPAredstarti(length(LPAredstarti))+45),'xx');
LPAred = E(LPAredstarti(1)+11:LPAredstarti(1)+LPAredendi(2)-2);
LPAred = regexprep(LPAred,'yy','\t');
LPAred = str2num(LPAred);
RPAyelstarti = strfind(E,'RPAyel');
RPAyelendi = strfind(E(RPAyelstarti(1):RPAyelstarti(length(RPAyelstarti))+45),'xx');
RPAyel = E(RPAyelstarti(1)+11:RPAyelstarti(1)+RPAyelendi(2)-2);
RPAyel = regexprep(RPAyel,'yy','\t');
RPAyel = str2num(RPAyel);
PFbluestarti = strfind(E,'PFblue');
PFblueendi = strfind(E(PFbluestarti(1):PFbluestarti(length(PFbluestarti))+45),'xx');
PFblue = E(PFbluestarti(1)+11:PFbluestarti(1)+PFblueendi(2)-2);
PFblue = regexprep(PFblue,'yy','\t');
PFblue = str2num(PFblue);
LPFwhstarti = strfind(E,'LPFwh');
LPFwhendi = strfind(E(LPFwhstarti(1):LPFwhstarti(length(LPFwhstarti))+45),'xx');
LPFwh = E(LPFwhstarti(1)+11:LPFwhstarti(1)+LPFwhendi(2)-2);
LPFwh = regexprep(LPFwh,'yy','\t');
LPFwh = str2num(LPFwh);
RPFblackstarti = strfind(E,'RPFblack');
RPFblackendi = strfind(E(RPFblackstarti(1):end),'xx');
RPFblack = E(RPFblackstarti(1)+11:RPFblackstarti(1)+RPFblackendi(2)-2);
RPFblack = regexprep(RPFblack,'yy','\t');
RPFblack = str2num(RPFblack);
allfids = [NASION;LPA;RPA;LPAred;RPAyel;PFblue;LPFwh;RPFblack];
fidslabels = {'NASION';'LPA';'RPA';'LPAred';'RPAyel';'PFblue';'LPFwh';'RPFblack'};
fid2 = fopen(hspfile);
C = fscanf(fid2,'%c');
fclose(fid2);
E = regexprep(C,'\r','xx'); %replace returns with "xx"
E = regexprep(E,'\t','yy'); %replace tabs with "yy"
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
headshapestarti = strfind(E,'position of digitized points');
headshapestartii = strfind(E(headshapestarti(1):end),'xx');
headshape = E(headshapestarti(1)+headshapestartii(2)+2:end);
headshape = regexprep(headshape,'yy','\t');
headshape = regexprep(headshape,'xx','');
headshape = str2num(headshape);
shape.pnt = headshape;
shape.fid.pnt = allfids;
shape.fid.label = fidslabels;
%convert to BESA style coordinates so can use the .pos file or sensor
%config from .con
% shape.pnt = cat(2,fliplr(shape.pnt(:,1:2)),shape.pnt(:,3)).*1000;
% %shape.pnt = shape.pnt(1:length(shape.pnt)-15,:); % get rid of nose points may want to alter or comment this depending on your digitisation
% %shape.pnt = shape.pnt*1000;
% neg = shape.pnt(:,2)*-1;
% shape.pnt(:,2) = neg;
%
% shape.fid.pnt = cat(2,fliplr(shape.fid.pnt(:,1:2)),shape.fid.pnt(:,3)).*1000;
% %shape.fid.pnt = shape.fid.pnt*1000;
% neg2 = shape.fid.pnt(:,2)*-1;
% shape.fid.pnt(:,2) = neg2;
% shape.unit='mm';
% shape = ft_convert_units(shape,'cm');
new_name2 = ['shape.mat'];
save (new_name2,'shape');
end
function [R,T,Yf,Err] = rot3dfit(X,Y)
%ROT3DFIT Determine least-square rigid rotation and translation.
% [R,T,Yf] = ROT3DFIT(X,Y) permforms a least-square fit for the
% linear form
%
% Y = X*R + T
%
% where R is a 3 x 3 orthogonal rotation matrix, T is a 1 x 3
% translation vector, and X and Y are 3D points sets defined as
% N x 3 matrices. Yf is the best-fit matrix.
%
% See also SVD, NORM.
%
% rot3dfit: Frank Evans, NHLBI/NIH, 30 November 2001
%
% ROT3DFIT uses the method described by K. S. Arun, T. S. Huang,and
% S. D. Blostein, "Least-Squares Fitting of Two 3-D Point Sets",
% IEEE Transactions on Pattern Analysis and Machine Intelligence,
% PAMI-9(5): 698 - 700, 1987.
%
% A better theoretical development is found in B. K. P. Horn,
% H. M. Hilden, and S. Negahdaripour, "Closed-form solution of
% absolute orientation using orthonormal matrices", Journal of the
% Optical Society of America A, 5(7): 1127 - 1135, 1988.
%
% Special cases, e.g. colinear and coplanar points, are not
% implemented.
%error(nargchk(2,2,nargin));
narginchk(2,2); %PFS Change to update
if size(X,2) ~= 3, error('X must be N x 3'); end;
if size(Y,2) ~= 3, error('Y must be N x 3'); end;
if size(X,1) ~= size(Y,1), error('X and Y must be the same size'); end;
% mean correct
Xm = mean(X,1); X1 = X - ones(size(X,1),1)*Xm;
Ym = mean(Y,1); Y1 = Y - ones(size(Y,1),1)*Ym;
% calculate best rotation using algorithm 12.4.1 from
% G. H. Golub and C. F. van Loan, "Matrix Computations"
% 2nd Edition, Baltimore: Johns Hopkins, 1989, p. 582.
XtY = (X1')*Y1;
[U,S,V] = svd(XtY);
R = U*(V');
% solve for the translation vector
T = Ym - Xm*R;
% calculate fit points
Yf = X*R + ones(size(X,1),1)*T;
% calculate the error
dY = Y - Yf;
Err = norm(dY,'fro'); % must use Frobenius norm
end
function [output] = ft_transform_geometry_PFS_hacked(transform, input)
% FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to
% a structure with geometric information, for example a volume conduction model
% for the head, gradiometer of electrode structure containing EEG or MEG
% sensor positions and MEG coil orientations, a head shape or a source model.
%
% The units in which the transformation matrix is expressed are assumed to
% be the same units as the units in which the geometric object is
% expressed. Depending on the input object, the homogeneous transformation
% matrix should be limited to a rigid-body translation plus rotation
% (MEG-gradiometer array), or to a rigid-body translation plus rotation
% plus a global rescaling (volume conductor geometry).
%
% Use as
% output = ft_transform_geometry(transform, input)
%
% See also FT_WARP_APPLY, FT_HEADCOORDINATES
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_transform_geometry.m$
% flg rescaling check
allowscaling = ~ft_senstype(input, 'meg');
% determine the rotation matrix
rotation = eye(4);
rotation(1:3,1:3) = transform(1:3,1:3);
if any(abs(transform(4,:)-[0 0 0 1])>100*eps)
error('invalid transformation matrix');
end
%%### get rid of this accuracy checking below as some of the transformation
%%matricies will be a bit hairy###
if ~allowscaling
% allow for some numerical imprecision
%if abs(det(rotation)-1)>1e-6%100*eps
%if abs(det(rotation)-1)>100*eps % allow for some numerical imprecision
%error('only a rigid body transformation without rescaling is allowed');
%end
end
if allowscaling
% FIXME build in a check for uniform rescaling probably do svd or so
% FIXME insert check for nonuniform scaling, should give an error
end
tfields = {'pos' 'pnt' 'o' 'coilpos' 'chanpos' 'chanposold' 'chanposorg' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation
rfields = {'ori' 'nrm' 'coilori' 'chanori' 'chanoriold' 'chanoriorg'}; % only apply rotation
mfields = {'transform'}; % plain matrix multiplication
recfields = {'fid' 'bnd' 'orig'}; % recurse into these fields
% the field 'r' is not included here, because it applies to a volume
% conductor model, and scaling is not allowed, so r will not change.
fnames = fieldnames(input);
for k = 1:numel(fnames)
if ~isempty(input.(fnames{k}))
if any(strcmp(fnames{k}, tfields))
input.(fnames{k}) = apply(transform, input.(fnames{k}));
elseif any(strcmp(fnames{k}, rfields))
input.(fnames{k}) = apply(rotation, input.(fnames{k}));
elseif any(strcmp(fnames{k}, mfields))
input.(fnames{k}) = transform*input.(fnames{k});
elseif any(strcmp(fnames{k}, recfields))
for j = 1:numel(input.(fnames{k}))
input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j));
end
else
% do nothing
end
end
end
output = input;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that applies the homogeneous transformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [new] = apply(transform, old)
old(:,4) = 1;
new = old * transform';
new = new(:,1:3);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rotate_about_z - make a rotation matix for arbitrary rotation in degrees
% around z axis
%
% Written by Paul Sowman Oct 2017 (http://web.iitd.ac.in/~hegde/cad/lecture/L6_3dtrans.pdf - page 4)
%
% INPUTS:
% - deg = degrees of rotation required
%
% OUTPUTS:
% - rmatx = a 4*4 rotation matrix for deg degrees about z
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rmatx=rotate_about_z(deg)
deg = deg2rad(deg);
rmatx = [cos(deg) sin(deg) 0 0;-sin(deg) cos(deg) 0 0;0 0 1 0;0 0 0 1];
end
function [headshape_downsampled] = downsample_headshape(path_to_headshape,numvertices)
% Get headshape
headshape = ft_read_headshape(path_to_headshape);
% Convert to cm
headshape = ft_convert_units(headshape,'cm');
% Convert to BESA co-ordinates
% headshape.pos = cat(2,fliplr(headshape.pos(:,1:2)),headshape.pos(:,3));
% headshape.pos(:,2) = headshape.pos(:,2).*-1;
% Get indices of facial points (up to 4cm above nasion)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Is 4cm the correct distance?
% Possibly different for child system?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
count_facialpoints = find(headshape.pos(:,3)<4);
if isempty(count_facialpoints)
disp('CANNOT FIND ANY FACIAL POINTS - COREG BY ICP MAY BE INACCURATE');
else
facialpoints = headshape.pos(count_facialpoints,:,:);
rrr = 1:4:length(facialpoints);
facialpoints = facialpoints(rrr,:); clear rrr;
end
% Remove facial points for now
headshape.pos(count_facialpoints,:) = [];
% Create mesh out of headshape downsampled to x points specified in the
% function call
cfg.numvertices = numvertices;
cfg.method = 'headshape';
cfg.headshape = headshape.pos;
mesh = ft_prepare_mesh(cfg, headshape);
% Replace the headshape info with the mesh points
headshape.pos = mesh.pos;
% Create figure for quality checking
figure; subplot(2,2,1);ft_plot_mesh(mesh); hold on;
title('Downsampled Mesh');
view(0,0);
subplot(2,2,2);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 1');
view(0,0);
subplot(2,2,3);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 2');
view(90,0);
subplot(2,2,4);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 3');
view(180,0);
print('headshape_quality','-dpdf');
% Add the facial info back in
headshape.pos = vertcat(headshape.pos,facialpoints);
% Add in names of the fiducials from the sensor
headshape.fid.label = {'NASION','LPA','RPA'};
% Convert fiducial points to BESA
% headshape.fid.pos = cat(2,fliplr(headshape.fid.pos(:,1:2)),headshape.fid.pos(:,3));
% headshape.fid.pos(:,2) = headshape.fid.pos(:,2).*-1;
% Plot for quality checking
figure;
ft_plot_headshape(headshape) %plot headshape
view(0,0);
print('headshape_quality2','-dpdf');
% Export filename
headshape_downsampled = headshape;
end
% Assign Weights Function
function y = assignweights(x, w)
% x is an indexing vector with the same number of arguments as w
y = w(:)';
end
end
|
github
|
Macquarie-MEG-Research/coreg-master
|
coreg_yokogawa_icp.m
|
.m
|
coreg-master/coreg_yokogawa_icp.m
| 22,584 |
utf_8
|
8138e2134eca27e911561b8ecaeed65f
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% coreg_yokogawa_icp is a function to coregister a structural MRI with MEG data
% and associated headshape information
%
% Written by Robert Seymour Oct/Nov 2017 (some subfunctions written by Paul
% Sowman)
%
% INPUTS:
% - dir_name = directory name for the output of your coreg
% - confile = full path to the con file
% - mrkfile = full path to the mrk file
% - mri_file = full path to the NIFTI structural MRI file
% - hspfile = full path to the hsp (polhemus headshape) file
% - elpfile = full path to the elp file
% - hsp_points = number of points for downsampling the headshape (try 100-200)
% - scalpthreshold = threshold for scalp extraction (try 0.05 if unsure)
%
% VARIABLE INPUTS (if using please specify all):
% - do_vids = save videos to file. Requires CaptureFigVid.
%
% EXAMPLE FUNCTION CALL:
% coreg_yokogawa_icp(dir_name,confile,mrkfile,mri_file,hspfile,elpfile,...
% hsp_points, scalpthreshold,'yes')
%
% OUTPUTS:
% - grad_trans = correctly aligned sensor layout
% - headshape_downsampled = downsampled headshape (original variable name I know)
% - mri_realigned = the mri realigned based on fiducial points
% - trans_matrix = transformation matrix for accurate coregistration
% - headmodel_singleshell = coregistered singleshell headmodel
%
% THIS IS A WORK IN PROGRESS FUNCTION - any updates or suggestions would be
% much appreciated
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function coreg_yokogawa_icp(dir_name,confile,mrkfile,mri_file,hspfile,elpfile,hsp_points,scalpthreshold,varargin)
if isempty(varargin)
do_vids = 'no';
else
do_vids = varargin{1};
end
cd(dir_name); disp('CDd to the right place');
% Get Polhemus Points
[shape] = parsePolhemus(elpfile,hspfile);
% Read the grads from the con file
grad_con = ft_read_sens(confile); %in cm, load grads
% Read the mrk file
mrk = ft_read_headshape(mrkfile,'format','yokogawa_mrk');
markers = mrk.fid.pos([2 3 1 4 5],:);%reorder mrk to match order in shape
[R,T,Yf,Err] = rot3dfit(markers,shape.fid.pnt(4:end,:));%calc rotation transform
meg2head_transm = [[R;T]'; 0 0 0 1];%reorganise and make 4*4 transformation matrix
% Transform sensors based on the MRKfile
grad_trans = ft_transform_geometry_PFS_hacked(meg2head_transm,grad_con); %Use my hacked version of the ft function - accuracy checking removed not sure if this is good or not
grad_trans.fid = shape; %add in the head information
% Rotate about z-axis
rot180mat = rotate_about_z(180);
grad_trans = ft_transform_geometry(rot180mat,grad_trans);
save grad_trans grad_trans
% Get headshape downsampled to 100 points with facial info preserved
headshape_downsampled = downsample_headshape(hspfile,hsp_points,grad_trans);
% Rotate about z-axis
headshape_downsampled = ft_transform_geometry(rot180mat,headshape_downsampled);
save headshape_downsampled headshape_downsampled
% Load in MRI
mri_orig = ft_read_mri(mri_file); % in mm, read in mri from DICOM
mri_orig = ft_convert_units(mri_orig,'cm'); mri_orig.coordsys = 'neuromag';
% Give rough estimate of fiducial points
cfg = [];
cfg.method = 'interactive';
cfg.viewmode = 'ortho';
cfg.coordsys = 'neuromag';
[mri_realigned] = ft_volumerealign(cfg, mri_orig);
save mri_realigned mri_realigned
% check that the MRI is consistent after realignment
ft_determine_coordsys(mri_realigned, 'interactive', 'no');
hold on; % add the subsequent objects to the figure
drawnow; % workaround to prevent some MATLAB versions (2012b and 2014b) from crashing
ft_plot_headshape(headshape_downsampled);
%% Extract Scalp Surface
cfg = [];
cfg.output = 'scalp';
cfg.scalpsmooth = 5;
cfg.scalpthreshold = scalpthreshold;
scalp = ft_volumesegment(cfg, mri_realigned);
%% Create mesh out of scalp surface
cfg = [];
cfg.method = 'projectmesh';
cfg.numvertices = 90000;
mesh = ft_prepare_mesh(cfg,scalp);
mesh = ft_convert_units(mesh,'cm');
% Flip the mesh around (improves coreg)
%mesh.pos(:,2) = mesh.pos(:,2).*-1;
%% Create Figure for Quality Checking
if strcmp(do_vids,'yes')
try
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on; drawnow;
view(0,0);
ft_plot_headshape(headshape_downsampled); drawnow;
OptionZ.FrameRate=15;OptionZ.Duration=5.5;OptionZ.Periodic=true;
CaptureFigVid([0,0; 360,0], 'mesh_quality',OptionZ)
catch
disp('You need CaptureFigVid in your MATLAB path. Download at https://goo.gl/Qr7GXb');
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on; drawnow;
ft_plot_headshape(headshape_downsampled); drawnow;
view(0,0);print('mesh_quality','-dpdf');
end
else
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on; drawnow;
view(90,0);
ft_plot_headshape(headshape_downsampled); drawnow;
title('If this looks weird you might want to adjust the cfg.scalpthreshold value');
print('mesh_quality','-dpdf');
end
%% Perform ICP using mesh and headshape information
numiter = 50;
disp('Performing ICP fit with 50 iterations');
[R, t, err, dummy, info] = icp(mesh.pos', headshape_downsampled.pos', numiter, 'Minimize', 'plane', 'Extrapolation', true, 'WorstRejection', 0.05);
%% Create figure to display how the ICP algorithm reduces error
clear plot;
figure; plot([1:1:51]',err,'LineWidth',8);
ylabel('Error'); xlabel('Iteration');
title('Error*Iteration');
set(gca,'FontSize',25);
%% Create transformation matrix
trans_matrix = inv([real(R) real(t);0 0 0 1]);
save trans_matrix trans_matrix
%% Create figure to assess accuracy of coregistration
mesh_spare = mesh;
mesh_spare.pos = ft_warp_apply(trans_matrix, mesh_spare.pos);
c = datestr(clock); %time and date
if strcmp(do_vids,'yes')
try
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
clear c; OptionZ.FrameRate=15;OptionZ.Duration=5.5;OptionZ.Periodic=true;
CaptureFigVid([0,0; 360,0], 'ICP_quality',OptionZ)
catch
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
clear c; print('ICP_quality','-dpdf');
disp('You need CaptureFigVid in your MATLAB path. Download at https://goo.gl/Qr7GXb');
end
else
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
clear c; print('ICP_quality','-dpdf');
end
%% Segment
cfg = [];
cfg.output = 'brain';
mri_segmented = ft_volumesegment(cfg, mri_realigned);
%% Create singleshell headmodel
cfg = [];
cfg.method='singleshell';
headmodel_singleshell = ft_prepare_headmodel(cfg, mri_segmented); % in cm, creat headmodel
% Flip headmodel around
%headmodel_singleshell.bnd.pos(:,2) = headmodel_singleshell.bnd.pos(:,2).*-1;
% Apply transformation matrix
headmodel_singleshell.bnd.pos = ft_warp_apply(trans_matrix,headmodel_singleshell.bnd.pos);
figure;ft_plot_headshape(headshape_downsampled) %plot headshape
ft_plot_sens(grad_trans, 'style', 'k*')
ft_plot_vol(headmodel_singleshell, 'facecolor', 'cortex', 'edgecolor', 'none');alpha 1; camlight
view([90,0]); title('After Coreg');
print('headmodel_quality','-dpdf');
save headmodel_singleshell headmodel_singleshell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUBFUNCTIONS
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [shape] = parsePolhemus(elpfile,hspfile)
fid1 = fopen(elpfile);
C = fscanf(fid1,'%c');
fclose(fid1);
E = regexprep(C,'\r','xx');
E = regexprep(E,'\t','yy');
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
sensornamesi = strfind(E,'%N');
fiducialsstarti = strfind(E,'%F');
lastfidendi = strfind(E(fiducialsstarti(3):fiducialsstarti(length(fiducialsstarti))+100),'xx');
fiducialsendi = fiducialsstarti(1)+strfind(E(fiducialsstarti(1):fiducialsstarti(length(fiducialsstarti))+lastfidendi(1)),'xx');
NASION = E(fiducialsstarti(1)+4:fiducialsendi(1)-2);
NASION = regexprep(NASION,'yy','\t');
NASION = str2num(NASION);
LPA = E(fiducialsstarti(2)+4:fiducialsendi(2)-2);
LPA = regexprep(LPA,'yy','\t');
LPA = str2num(LPA);
RPA = E(fiducialsstarti(3)+4:fiducialsendi(3)-2);
RPA = regexprep(RPA,'yy','\t');
RPA = str2num(RPA);
LPAredstarti = strfind(E,'LPAred');
LPAredendi = strfind(E(LPAredstarti(1):LPAredstarti(length(LPAredstarti))+45),'xx');
LPAred = E(LPAredstarti(1)+11:LPAredstarti(1)+LPAredendi(2)-2);
LPAred = regexprep(LPAred,'yy','\t');
LPAred = str2num(LPAred);
RPAyelstarti = strfind(E,'RPAyel');
RPAyelendi = strfind(E(RPAyelstarti(1):RPAyelstarti(length(RPAyelstarti))+45),'xx');
RPAyel = E(RPAyelstarti(1)+11:RPAyelstarti(1)+RPAyelendi(2)-2);
RPAyel = regexprep(RPAyel,'yy','\t');
RPAyel = str2num(RPAyel);
PFbluestarti = strfind(E,'PFblue');
PFblueendi = strfind(E(PFbluestarti(1):PFbluestarti(length(PFbluestarti))+45),'xx');
PFblue = E(PFbluestarti(1)+11:PFbluestarti(1)+PFblueendi(2)-2);
PFblue = regexprep(PFblue,'yy','\t');
PFblue = str2num(PFblue);
LPFwhstarti = strfind(E,'LPFwh');
LPFwhendi = strfind(E(LPFwhstarti(1):LPFwhstarti(length(LPFwhstarti))+45),'xx');
LPFwh = E(LPFwhstarti(1)+11:LPFwhstarti(1)+LPFwhendi(2)-2);
LPFwh = regexprep(LPFwh,'yy','\t');
LPFwh = str2num(LPFwh);
RPFblackstarti = strfind(E,'RPFblack');
RPFblackendi = strfind(E(RPFblackstarti(1):end),'xx');
RPFblack = E(RPFblackstarti(1)+11:RPFblackstarti(1)+RPFblackendi(2)-2);
RPFblack = regexprep(RPFblack,'yy','\t');
RPFblack = str2num(RPFblack);
allfids = [NASION;LPA;RPA;LPAred;RPAyel;PFblue;LPFwh;RPFblack];
fidslabels = {'NASION';'LPA';'RPA';'LPAred';'RPAyel';'PFblue';'LPFwh';'RPFblack'};
fid2 = fopen(hspfile);
C = fscanf(fid2,'%c');
fclose(fid2);
E = regexprep(C,'\r','xx'); %replace returns with "xx"
E = regexprep(E,'\t','yy'); %replace tabs with "yy"
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
headshapestarti = strfind(E,'position of digitized points');
headshapestartii = strfind(E(headshapestarti(1):end),'xx');
headshape = E(headshapestarti(1)+headshapestartii(2)+2:end);
headshape = regexprep(headshape,'yy','\t');
headshape = regexprep(headshape,'xx','');
headshape = str2num(headshape);
shape.pnt = headshape;
shape.fid.pnt = allfids;
shape.fid.label = fidslabels;
%convert to BESA style coordinates so can use the .pos file or sensor
%config from .con
shape.pnt = cat(2,fliplr(shape.pnt(:,1:2)),shape.pnt(:,3)).*1000;
%shape.pnt = shape.pnt(1:length(shape.pnt)-15,:); % get rid of nose points may want to alter or comment this depending on your digitisation
%shape.pnt = shape.pnt*1000;
neg = shape.pnt(:,2)*-1;
shape.pnt(:,2) = neg;
shape.fid.pnt = cat(2,fliplr(shape.fid.pnt(:,1:2)),shape.fid.pnt(:,3)).*1000;
%shape.fid.pnt = shape.fid.pnt*1000;
neg2 = shape.fid.pnt(:,2)*-1;
shape.fid.pnt(:,2) = neg2;
shape.unit='mm';
shape = ft_convert_units(shape,'cm');
new_name2 = ['shape.mat'];
save (new_name2,'shape');
end
function [R,T,Yf,Err] = rot3dfit(X,Y)
%ROT3DFIT Determine least-square rigid rotation and translation.
% [R,T,Yf] = ROT3DFIT(X,Y) permforms a least-square fit for the
% linear form
%
% Y = X*R + T
%
% where R is a 3 x 3 orthogonal rotation matrix, T is a 1 x 3
% translation vector, and X and Y are 3D points sets defined as
% N x 3 matrices. Yf is the best-fit matrix.
%
% See also SVD, NORM.
%
% rot3dfit: Frank Evans, NHLBI/NIH, 30 November 2001
%
% ROT3DFIT uses the method described by K. S. Arun, T. S. Huang,and
% S. D. Blostein, "Least-Squares Fitting of Two 3-D Point Sets",
% IEEE Transactions on Pattern Analysis and Machine Intelligence,
% PAMI-9(5): 698 - 700, 1987.
%
% A better theoretical development is found in B. K. P. Horn,
% H. M. Hilden, and S. Negahdaripour, "Closed-form solution of
% absolute orientation using orthonormal matrices", Journal of the
% Optical Society of America A, 5(7): 1127 - 1135, 1988.
%
% Special cases, e.g. colinear and coplanar points, are not
% implemented.
%error(nargchk(2,2,nargin));
narginchk(2,2); %PFS Change to update
if size(X,2) ~= 3, error('X must be N x 3'); end;
if size(Y,2) ~= 3, error('Y must be N x 3'); end;
if size(X,1) ~= size(Y,1), error('X and Y must be the same size'); end;
% mean correct
Xm = mean(X,1); X1 = X - ones(size(X,1),1)*Xm;
Ym = mean(Y,1); Y1 = Y - ones(size(Y,1),1)*Ym;
% calculate best rotation using algorithm 12.4.1 from
% G. H. Golub and C. F. van Loan, "Matrix Computations"
% 2nd Edition, Baltimore: Johns Hopkins, 1989, p. 582.
XtY = (X1')*Y1;
[U,S,V] = svd(XtY);
R = U*(V');
% solve for the translation vector
T = Ym - Xm*R;
% calculate fit points
Yf = X*R + ones(size(X,1),1)*T;
% calculate the error
dY = Y - Yf;
Err = norm(dY,'fro'); % must use Frobenius norm
end
function [output] = ft_transform_geometry_PFS_hacked(transform, input)
% FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to
% a structure with geometric information, for example a volume conduction model
% for the head, gradiometer of electrode structure containing EEG or MEG
% sensor positions and MEG coil orientations, a head shape or a source model.
%
% The units in which the transformation matrix is expressed are assumed to
% be the same units as the units in which the geometric object is
% expressed. Depending on the input object, the homogeneous transformation
% matrix should be limited to a rigid-body translation plus rotation
% (MEG-gradiometer array), or to a rigid-body translation plus rotation
% plus a global rescaling (volume conductor geometry).
%
% Use as
% output = ft_transform_geometry(transform, input)
%
% See also FT_WARP_APPLY, FT_HEADCOORDINATES
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_transform_geometry.m$
% flg rescaling check
allowscaling = ~ft_senstype(input, 'meg');
% determine the rotation matrix
rotation = eye(4);
rotation(1:3,1:3) = transform(1:3,1:3);
if any(abs(transform(4,:)-[0 0 0 1])>100*eps)
error('invalid transformation matrix');
end
%%### get rid of this accuracy checking below as some of the transformation
%%matricies will be a bit hairy###
if ~allowscaling
% allow for some numerical imprecision
%if abs(det(rotation)-1)>1e-6%100*eps
%if abs(det(rotation)-1)>100*eps % allow for some numerical imprecision
%error('only a rigid body transformation without rescaling is allowed');
%end
end
if allowscaling
% FIXME build in a check for uniform rescaling probably do svd or so
% FIXME insert check for nonuniform scaling, should give an error
end
tfields = {'pos' 'pnt' 'o' 'coilpos' 'chanpos' 'chanposold' 'chanposorg' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation
rfields = {'ori' 'nrm' 'coilori' 'chanori' 'chanoriold' 'chanoriorg'}; % only apply rotation
mfields = {'transform'}; % plain matrix multiplication
recfields = {'fid' 'bnd' 'orig'}; % recurse into these fields
% the field 'r' is not included here, because it applies to a volume
% conductor model, and scaling is not allowed, so r will not change.
fnames = fieldnames(input);
for k = 1:numel(fnames)
if ~isempty(input.(fnames{k}))
if any(strcmp(fnames{k}, tfields))
input.(fnames{k}) = apply(transform, input.(fnames{k}));
elseif any(strcmp(fnames{k}, rfields))
input.(fnames{k}) = apply(rotation, input.(fnames{k}));
elseif any(strcmp(fnames{k}, mfields))
input.(fnames{k}) = transform*input.(fnames{k});
elseif any(strcmp(fnames{k}, recfields))
for j = 1:numel(input.(fnames{k}))
input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j));
end
else
% do nothing
end
end
end
output = input;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that applies the homogeneous transformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [new] = apply(transform, old)
old(:,4) = 1;
new = old * transform';
new = new(:,1:3);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rotate_about_z - make a rotation matix for arbitrary rotation in degrees
% around z axis
%
% Written by Paul Sowman Oct 2017 (http://web.iitd.ac.in/~hegde/cad/lecture/L6_3dtrans.pdf - page 4)
%
% INPUTS:
% - deg = degrees of rotation required
%
% OUTPUTS:
% - rmatx = a 4*4 rotation matrix for deg degrees about z
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rmatx=rotate_about_z(deg)
deg = deg2rad(deg);
rmatx = [cos(deg) sin(deg) 0 0;-sin(deg) cos(deg) 0 0;0 0 1 0;0 0 0 1];
end
function [headshape_downsampled] = downsample_headshape(path_to_headshape,numvertices,sensors)
% Get headshape
headshape = ft_read_headshape(path_to_headshape);
% Convert to cm
headshape = ft_convert_units(headshape,'cm');
% Convert to BESA co-ordinates
headshape.pos = cat(2,fliplr(headshape.pos(:,1:2)),headshape.pos(:,3));
headshape.pos(:,2) = headshape.pos(:,2).*-1;
% Get indices of facial points (up to 4cm above nasion)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Is 4cm the correct distance?
% Possibly different for child system?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
count_facialpoints = find(headshape.pos(:,3)<4);
if isempty(count_facialpoints)
disp('CANNOT FIND ANY FACIAL POINTS - COREG BY ICP MAY BE INACCURATE');
else
facialpoints = headshape.pos(count_facialpoints,:,:);
rrr = 1:4:length(facialpoints);
facialpoints = facialpoints(rrr,:); clear rrr;
end
% Remove facial points for now
headshape.pos(count_facialpoints,:) = [];
% Create mesh out of headshape downsampled to x points specified in the
% function call
cfg.numvertices = numvertices;
cfg.method = 'headshape';
cfg.headshape = headshape.pos;
mesh = ft_prepare_mesh(cfg, headshape);
% Replace the headshape info with the mesh points
headshape.pos = mesh.pos;
% Create figure for quality checking
figure; subplot(2,2,1);ft_plot_mesh(mesh); hold on;
title('Downsampled Mesh');
view(0,0);
subplot(2,2,2);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 1');
view(0,0);
subplot(2,2,3);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 2');
view(90,0);
subplot(2,2,4);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 3');
view(180,0);
print('headshape_quality','-dpdf');
% Add the facial info back in
headshape.pos = vertcat(headshape.pos,facialpoints);
% Add in names of the fiducials from the sensor
headshape.fid.label = {'NASION','LPA','RPA'};
% Convert fiducial points to BESA
headshape.fid.pos = cat(2,fliplr(headshape.fid.pos(:,1:2)),headshape.fid.pos(:,3));
headshape.fid.pos(:,2) = headshape.fid.pos(:,2).*-1;
% Plot for quality checking
figure;ft_plot_sens(sensors) %plot channel position : between the 1st and 2nd coils
ft_plot_headshape(headshape) %plot headshape
view(0,0);
print('headshape_quality2','-dpdf');
% Export filename
headshape_downsampled = headshape;
end
end
|
github
|
Macquarie-MEG-Research/coreg-master
|
rotate_about_z.m
|
.m
|
coreg-master/rotate_about_z.m
| 639 |
utf_8
|
0ac9e04e0dc642327777e1e34c1fa83b
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rotate_about_z - make a rotation matix for arbitrary rotation in degrees
% around z axis
%
% Written by Paul Sowman Oct 2017 (http://web.iitd.ac.in/~hegde/cad/lecture/L6_3dtrans.pdf - page 4)
%
% INPUTS:
% - deg = degrees of rotation required
%
% OUTPUTS:
% - rmatx = a 4*4 rotation matrix for deg degrees about z
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rmatx=rotate_about_z(deg)
deg = deg2rad(deg);
rmatx = [cos(deg) sin(deg) 0 0;-sin(deg) cos(deg) 0 0;0 0 1 0;0 0 0 1];
end
|
github
|
Macquarie-MEG-Research/coreg-master
|
coreg_elekta_icp_adjust_weights.m
|
.m
|
coreg-master/coreg_elekta_icp_adjust_weights.m
| 26,871 |
utf_8
|
9efae39ef831a6a6034f4f1c34f5c6e0
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% coreg_yokogawa_icp_adjust_weights is a function to coregister a structural
% MRI with MEG data and associated headshape information
%
% Written by Robert Seymour Oct 2017 - Feb 2018 (some subfunctions
% contributed by Paul Sowman)
%
% INPUTS:
% - dir_name = directory name for the output of your coreg
% - confile = full path to the con file
% - mrkfile = full path to the mrk file
% - mri_file = full path to the NIFTI structural MRI file
% - hspfile = full path to the hsp (polhemus headshape) file
% - elpfile = full path to the elp file
% - hsp_points = number of points for downsampling the headshape (try 100-200)
% - scalpthreshold = threshold for scalp extraction (try 0.05 if unsure)
%
% VARIABLE INPUTS (if using please specify all):
% - do_vids = save videos to file. Requires CaptureFigVid.
% - weight_number = how strongly do you want to weight the facial points?
% - bad_coil = is there a bad coil to take out?
%
% EXAMPLE FUNCTION CALL:
% coreg_yokogawa_icp_adjust_weights(dir_name,confile,mrkfile,mri_file,...
% hspfile,elpfile,hsp_points, scalpthreshold,'yes',0.8,'')
%
% OUTPUTS:
% - grad_trans = correctly aligned sensor layout
% - headshape_downsampled = downsampled headshape (original variable name I know)
% - mri_realigned = the mri realigned based on fiducial points
% - trans_matrix = transformation matrix for accurate coregistration
% - mri_realigned2 = the coregistered mri based on ICP algorithm
% - headmodel_singleshell = coregistered singleshell headmodel
%
% THIS IS A WORK IN PROGRESS FUNCTION - any updates or suggestions would be
% much appreciated
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function coreg_yokogawa_icp_adjust_weights(dir_name,confile,mrkfile,mri_file,hspfile,elpfile,hsp_points,scalpthreshold,varargin)
if isempty(varargin)
do_vids = 'no';
weight_number = 0.1;
bad_coil = '';
else
do_vids = varargin{1};
weight_number = 1./varargin{2};
bad_coil = varargin{3}
end
cd(dir_name); disp('CDd to the right place');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Load initial variables & check the input of the function
% Get Polhemus Points
disp('Reading elp and headshape data');
[shape] = parsePolhemus(elpfile,hspfile);
shape = ft_convert_units(shape,'cm');
% Read the grads from the con file
disp('Reading sensor data from con file');
grad_con = ft_read_sens(confile); %load grads
grad_con = ft_convert_units(grad_con,'cm'); %in cm
% Read mrk_file
disp('Reading the mrk file');
mrk = ft_read_headshape(mrkfile,'format','yokogawa_mrk');
mrk = ft_convert_units(mrk,'cm'); %in cm
% Get headshape downsampled to specified no. of points
% with facial info preserved
fprintf('Downsampling headshape information to %d points whilst preserving facial information\n'...
,hsp_points);
headshape_downsampled = downsample_headshape(hspfile,hsp_points);
% Load in MRI
disp('Reading the MRI file');
mri_orig = ft_read_mri(mri_file); % in mm, read in mri from DICOM
mri_orig = ft_convert_units(mri_orig,'cm');
mri_orig.coordsys = 'neuromag';
% MRI...
% Give rough estimate of fiducial points
cfg = [];
cfg.method = 'interactive';
cfg.viewmode = 'ortho';
cfg.coordsys = 'bti';
[mri_realigned] = ft_volumerealign(cfg, mri_orig);
disp('Saving the first realigned MRI');
%save mri_realigned mri_realigned
% check that the MRI is consistent after realignment
ft_determine_coordsys(mri_realigned, 'interactive', 'no');
hold on; % add the subsequent objects to the figure
drawnow; % workaround to prevent some MATLAB versions (2012b and 2014b) from crashing
ft_plot_headshape(headshape_downsampled);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
% If there is no bad marker perform coreg normally
if isempty(bad_coil)
markers = mrk.fid.pos([2 3 1 4 5],:);%reorder mrk to match order in shape
[R,T,Yf,Err] = rot3dfit(markers,shape.fid.pnt(4:end,:));%calc rotation transform
meg2head_transm = [[R;T]'; 0 0 0 1];%reorganise and make 4*4 transformation matrix
grad_trans = ft_transform_geometry_PFS_hacked(meg2head_transm,grad_con); %Use my hacked version of the ft function - accuracy checking removed not sure if this is good or not
grad_trans.fid = shape; %add in the head information
save grad_trans grad_trans
% Else if there is a bad marker take out this info and perform coreg
else
fprintf(''); disp('TAKING OUT BAD MARKER');
% Identify the bad coil
badcoilpos = find(ismember(shape.fid.label,bad_coil));
% Take away the bad marker
marker_order = [2 3 1 4 5];
markers = mrk.fid.pos(marker_order,:);%reorder mrk to match order in shape
% Now take out the bad marker when you realign
markers(badcoilpos-3,:) = [];
fids_2_use = shape.fid.pnt(4:end,:); fids_2_use(badcoilpos-3,:) = [];
[R,T,Yf,Err] = rot3dfit(markers,fids_2_use);%calc rotation transform
meg2head_transm = [[R;T]'; 0 0 0 1];%reorganise and make 4*4 transformation matrix
grad_trans = ft_transform_geometry_PFS_hacked(meg2head_transm,grad_con); %Use my hacked version of the ft function - accuracy checking removed not sure if this is good or not
grad_trans.fid = shape; %add in the head information
save grad_trans grad_trans
end
%% Extract Scalp Surface
cfg = [];
cfg.output = 'scalp';
cfg.scalpsmooth = 5;
cfg.scalpthreshold = scalpthreshold;
scalp = ft_volumesegment(cfg, mri_realigned);
%% Create mesh out of scalp surface
cfg = [];
cfg.method = 'isosurface';
cfg.numvertices = 10000;
mesh = ft_prepare_mesh(cfg,scalp);
mesh = ft_convert_units(mesh,'cm');
%% Create Figure for Quality Checking
if strcmp(do_vids,'yes')
try
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull
hold on; drawnow; view(0,0);
ft_plot_headshape(headshape_downsampled); drawnow;
OptionZ.FrameRate=15;OptionZ.Duration=5.5;OptionZ.Periodic=true;
CaptureFigVid([0,0; 360,0], 'mesh_quality',OptionZ)
catch
disp('You need CaptureFigVid in your MATLAB path. Download at https://goo.gl/Qr7GXb');
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull
hold on; drawnow;
ft_plot_headshape(headshape_downsampled); drawnow;
view(0,0);print('mesh_quality','-dpng');
end
else
figure;
ft_plot_mesh(mesh,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull
hold on; drawnow;
view(90,0);
ft_plot_headshape(headshape_downsampled); drawnow;
title('If this looks weird you might want to adjust the cfg.scalpthreshold value');
print('mesh_quality','-dpng');
end
%% Perform ICP using mesh and headshape information
numiter = 50;
disp('Performing ICP fit with 50 iterations\n');
% Weight the facial points x10 times higher than the head points
count_facialpoints2 = find(headshape_downsampled.pos(:,3)<3); x = 1;
% If there are no facial points ignore the weighting
if isempty(count_facialpoints2)
w = ones(size(headshape_downsampled.pos,1),1).*1;
weights = @(x)assignweights(x,w);
disp('NOT Applying Weighting\n');
% But if there are facial points apply weighting using weight_number
else
w = ones(size(headshape_downsampled.pos,1),1).*weight_number;
w(count_facialpoints2) = 1;
weights = @(x)assignweights(x,w);
fprintf('Applying Weighting of %d \n',weight_number);
end
% Now try ICP with weights
[R, t, err] = icp(mesh.pos', headshape_downsampled.pos', numiter, 'Minimize', 'plane', 'Extrapolation', true, 'Weight', weights, 'WorstRejection', 0.05);
%% Create figure to display how the ICP algorithm reduces error
clear plot;
figure; plot([1:1:51]',err,'LineWidth',8);
ylabel('Error'); xlabel('Iteration');
title('Error*Iteration');
set(gca,'FontSize',25);
%% Create transformation matrix
trans_matrix = inv([real(R) real(t);0 0 0 1]);
save trans_matrix trans_matrix
%% Create figure to assess accuracy of coregistration
mesh_spare = mesh;
mesh_spare.pos = ft_warp_apply(trans_matrix, mesh_spare.pos);
c = datestr(clock); %time and date
if strcmp(do_vids,'yes')
try
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
OptionZ.FrameRate=15;OptionZ.Duration=5.5;OptionZ.Periodic=true;
CaptureFigVid([0,0; 360,0], 'ICP_quality',OptionZ)
catch
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
print('ICP_quality','-dpng');
disp('You need CaptureFigVid in your MATLAB path. Download at https://goo.gl/Qr7GXb');
end
else
figure;
ft_plot_mesh(mesh_spare,'facecolor',[238,206,179]./255,'EdgeColor','none','facealpha',0.8); hold on;
camlight; lighting phong; camlight left; camlight right; material dull; hold on;
ft_plot_headshape(headshape_downsampled); title(sprintf('%s. Error of ICP fit = %d' , c, err(end)));
clear c; print('ICP_quality','-dpng');
end
%% Apply transform to the MRI
mri_realigned2 = ft_transform_geometry(trans_matrix,mri_realigned);
save mri_realigned2 mri_realigned2
% check that the MRI is consistent after realignment
ft_determine_coordsys(mri_realigned2, 'interactive', 'no');
hold on; % add the subsequent objects to the figure
drawnow; % workaround to prevent some MATLAB versions (2012b and 2014b) from crashing
ft_plot_headshape(headshape_downsampled);
%% Segment
cfg = [];
cfg.output = 'brain';
mri_segmented = ft_volumesegment(cfg, mri_realigned2);
%% Create singleshell headmodel
cfg = [];
cfg.method='singleshell';
headmodel_singleshell = ft_prepare_headmodel(cfg, mri_segmented); % in cm, create headmodel
% Flip headmodel around
%headmodel_singleshell.bnd.pos(:,2) = headmodel_singleshell.bnd.pos(:,2).*-1;
% Apply transformation matrix
%headmodel_singleshell.bnd.pos = ft_warp_apply(trans_matrix,headmodel_singleshell.bnd.pos);
figure;ft_plot_headshape(headshape_downsampled) %plot headshape
ft_plot_sens(grad_trans, 'style', 'k*')
ft_plot_vol(headmodel_singleshell, 'facecolor', 'cortex', 'edgecolor', 'cortex'); alpha(1.0); hold on;
ft_plot_mesh(mesh_spare,'facecolor','skin'); alpha(0.2);
camlight left; camlight right; material dull; hold on;
view([90,0]); title('After Coreg');
print('headmodel_quality','-dpdf');
save headmodel_singleshell headmodel_singleshell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUBFUNCTIONS
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [shape] = parsePolhemus(elpfile,hspfile)
fid1 = fopen(elpfile);
C = fscanf(fid1,'%c');
fclose(fid1);
E = regexprep(C,'\r','xx');
E = regexprep(E,'\t','yy');
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
sensornamesi = strfind(E,'%N');
fiducialsstarti = strfind(E,'%F');
lastfidendi = strfind(E(fiducialsstarti(3):fiducialsstarti(length(fiducialsstarti))+100),'xx');
fiducialsendi = fiducialsstarti(1)+strfind(E(fiducialsstarti(1):fiducialsstarti(length(fiducialsstarti))+lastfidendi(1)),'xx');
NASION = E(fiducialsstarti(1)+4:fiducialsendi(1)-2);
NASION = regexprep(NASION,'yy','\t');
NASION = str2num(NASION);
LPA = E(fiducialsstarti(2)+4:fiducialsendi(2)-2);
LPA = regexprep(LPA,'yy','\t');
LPA = str2num(LPA);
RPA = E(fiducialsstarti(3)+4:fiducialsendi(3)-2);
RPA = regexprep(RPA,'yy','\t');
RPA = str2num(RPA);
LPAredstarti = strfind(E,'LPAred');
LPAredendi = strfind(E(LPAredstarti(1):LPAredstarti(length(LPAredstarti))+45),'xx');
LPAred = E(LPAredstarti(1)+11:LPAredstarti(1)+LPAredendi(2)-2);
LPAred = regexprep(LPAred,'yy','\t');
LPAred = str2num(LPAred);
RPAyelstarti = strfind(E,'RPAyel');
RPAyelendi = strfind(E(RPAyelstarti(1):RPAyelstarti(length(RPAyelstarti))+45),'xx');
RPAyel = E(RPAyelstarti(1)+11:RPAyelstarti(1)+RPAyelendi(2)-2);
RPAyel = regexprep(RPAyel,'yy','\t');
RPAyel = str2num(RPAyel);
PFbluestarti = strfind(E,'PFblue');
PFblueendi = strfind(E(PFbluestarti(1):PFbluestarti(length(PFbluestarti))+45),'xx');
PFblue = E(PFbluestarti(1)+11:PFbluestarti(1)+PFblueendi(2)-2);
PFblue = regexprep(PFblue,'yy','\t');
PFblue = str2num(PFblue);
LPFwhstarti = strfind(E,'LPFwh');
LPFwhendi = strfind(E(LPFwhstarti(1):LPFwhstarti(length(LPFwhstarti))+45),'xx');
LPFwh = E(LPFwhstarti(1)+11:LPFwhstarti(1)+LPFwhendi(2)-2);
LPFwh = regexprep(LPFwh,'yy','\t');
LPFwh = str2num(LPFwh);
RPFblackstarti = strfind(E,'RPFblack');
RPFblackendi = strfind(E(RPFblackstarti(1):end),'xx');
RPFblack = E(RPFblackstarti(1)+11:RPFblackstarti(1)+RPFblackendi(2)-2);
RPFblack = regexprep(RPFblack,'yy','\t');
RPFblack = str2num(RPFblack);
allfids = [NASION;LPA;RPA;LPAred;RPAyel;PFblue;LPFwh;RPFblack];
fidslabels = {'NASION';'LPA';'RPA';'LPAred';'RPAyel';'PFblue';'LPFwh';'RPFblack'};
fid2 = fopen(hspfile);
C = fscanf(fid2,'%c');
fclose(fid2);
E = regexprep(C,'\r','xx'); %replace returns with "xx"
E = regexprep(E,'\t','yy'); %replace tabs with "yy"
returnsi = strfind(E,'xx');
tabsi = strfind(E,'yy');
headshapestarti = strfind(E,'position of digitized points');
headshapestartii = strfind(E(headshapestarti(1):end),'xx');
headshape = E(headshapestarti(1)+headshapestartii(2)+2:end);
headshape = regexprep(headshape,'yy','\t');
headshape = regexprep(headshape,'xx','');
headshape = str2num(headshape);
shape.pnt = headshape;
shape.fid.pnt = allfids;
shape.fid.label = fidslabels;
%convert to BESA style coordinates so can use the .pos file or sensor
%config from .con
% shape.pnt = cat(2,fliplr(shape.pnt(:,1:2)),shape.pnt(:,3)).*1000;
% %shape.pnt = shape.pnt(1:length(shape.pnt)-15,:); % get rid of nose points may want to alter or comment this depending on your digitisation
% %shape.pnt = shape.pnt*1000;
% neg = shape.pnt(:,2)*-1;
% shape.pnt(:,2) = neg;
%
% shape.fid.pnt = cat(2,fliplr(shape.fid.pnt(:,1:2)),shape.fid.pnt(:,3)).*1000;
% %shape.fid.pnt = shape.fid.pnt*1000;
% neg2 = shape.fid.pnt(:,2)*-1;
% shape.fid.pnt(:,2) = neg2;
% shape.unit='mm';
% shape = ft_convert_units(shape,'cm');
new_name2 = ['shape.mat'];
save (new_name2,'shape');
end
function [R,T,Yf,Err] = rot3dfit(X,Y)
%ROT3DFIT Determine least-square rigid rotation and translation.
% [R,T,Yf] = ROT3DFIT(X,Y) permforms a least-square fit for the
% linear form
%
% Y = X*R + T
%
% where R is a 3 x 3 orthogonal rotation matrix, T is a 1 x 3
% translation vector, and X and Y are 3D points sets defined as
% N x 3 matrices. Yf is the best-fit matrix.
%
% See also SVD, NORM.
%
% rot3dfit: Frank Evans, NHLBI/NIH, 30 November 2001
%
% ROT3DFIT uses the method described by K. S. Arun, T. S. Huang,and
% S. D. Blostein, "Least-Squares Fitting of Two 3-D Point Sets",
% IEEE Transactions on Pattern Analysis and Machine Intelligence,
% PAMI-9(5): 698 - 700, 1987.
%
% A better theoretical development is found in B. K. P. Horn,
% H. M. Hilden, and S. Negahdaripour, "Closed-form solution of
% absolute orientation using orthonormal matrices", Journal of the
% Optical Society of America A, 5(7): 1127 - 1135, 1988.
%
% Special cases, e.g. colinear and coplanar points, are not
% implemented.
%error(nargchk(2,2,nargin));
narginchk(2,2); %PFS Change to update
if size(X,2) ~= 3, error('X must be N x 3'); end;
if size(Y,2) ~= 3, error('Y must be N x 3'); end;
if size(X,1) ~= size(Y,1), error('X and Y must be the same size'); end;
% mean correct
Xm = mean(X,1); X1 = X - ones(size(X,1),1)*Xm;
Ym = mean(Y,1); Y1 = Y - ones(size(Y,1),1)*Ym;
% calculate best rotation using algorithm 12.4.1 from
% G. H. Golub and C. F. van Loan, "Matrix Computations"
% 2nd Edition, Baltimore: Johns Hopkins, 1989, p. 582.
XtY = (X1')*Y1;
[U,S,V] = svd(XtY);
R = U*(V');
% solve for the translation vector
T = Ym - Xm*R;
% calculate fit points
Yf = X*R + ones(size(X,1),1)*T;
% calculate the error
dY = Y - Yf;
Err = norm(dY,'fro'); % must use Frobenius norm
end
function [output] = ft_transform_geometry_PFS_hacked(transform, input)
% FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to
% a structure with geometric information, for example a volume conduction model
% for the head, gradiometer of electrode structure containing EEG or MEG
% sensor positions and MEG coil orientations, a head shape or a source model.
%
% The units in which the transformation matrix is expressed are assumed to
% be the same units as the units in which the geometric object is
% expressed. Depending on the input object, the homogeneous transformation
% matrix should be limited to a rigid-body translation plus rotation
% (MEG-gradiometer array), or to a rigid-body translation plus rotation
% plus a global rescaling (volume conductor geometry).
%
% Use as
% output = ft_transform_geometry(transform, input)
%
% See also FT_WARP_APPLY, FT_HEADCOORDINATES
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_transform_geometry.m$
% flg rescaling check
allowscaling = ~ft_senstype(input, 'meg');
% determine the rotation matrix
rotation = eye(4);
rotation(1:3,1:3) = transform(1:3,1:3);
if any(abs(transform(4,:)-[0 0 0 1])>100*eps)
error('invalid transformation matrix');
end
%%### get rid of this accuracy checking below as some of the transformation
%%matricies will be a bit hairy###
if ~allowscaling
% allow for some numerical imprecision
%if abs(det(rotation)-1)>1e-6%100*eps
%if abs(det(rotation)-1)>100*eps % allow for some numerical imprecision
%error('only a rigid body transformation without rescaling is allowed');
%end
end
if allowscaling
% FIXME build in a check for uniform rescaling probably do svd or so
% FIXME insert check for nonuniform scaling, should give an error
end
tfields = {'pos' 'pnt' 'o' 'coilpos' 'chanpos' 'chanposold' 'chanposorg' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation
rfields = {'ori' 'nrm' 'coilori' 'chanori' 'chanoriold' 'chanoriorg'}; % only apply rotation
mfields = {'transform'}; % plain matrix multiplication
recfields = {'fid' 'bnd' 'orig'}; % recurse into these fields
% the field 'r' is not included here, because it applies to a volume
% conductor model, and scaling is not allowed, so r will not change.
fnames = fieldnames(input);
for k = 1:numel(fnames)
if ~isempty(input.(fnames{k}))
if any(strcmp(fnames{k}, tfields))
input.(fnames{k}) = apply(transform, input.(fnames{k}));
elseif any(strcmp(fnames{k}, rfields))
input.(fnames{k}) = apply(rotation, input.(fnames{k}));
elseif any(strcmp(fnames{k}, mfields))
input.(fnames{k}) = transform*input.(fnames{k});
elseif any(strcmp(fnames{k}, recfields))
for j = 1:numel(input.(fnames{k}))
input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j));
end
else
% do nothing
end
end
end
output = input;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that applies the homogeneous transformation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [new] = apply(transform, old)
old(:,4) = 1;
new = old * transform';
new = new(:,1:3);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rotate_about_z - make a rotation matix for arbitrary rotation in degrees
% around z axis
%
% Written by Paul Sowman Oct 2017 (http://web.iitd.ac.in/~hegde/cad/lecture/L6_3dtrans.pdf - page 4)
%
% INPUTS:
% - deg = degrees of rotation required
%
% OUTPUTS:
% - rmatx = a 4*4 rotation matrix for deg degrees about z
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rmatx=rotate_about_z(deg)
deg = deg2rad(deg);
rmatx = [cos(deg) sin(deg) 0 0;-sin(deg) cos(deg) 0 0;0 0 1 0;0 0 0 1];
end
function [headshape_downsampled] = downsample_headshape(path_to_headshape,numvertices)
% Get headshape
headshape = ft_read_headshape(path_to_headshape);
% Convert to cm
headshape = ft_convert_units(headshape,'cm');
% Convert to BESA co-ordinates
% headshape.pos = cat(2,fliplr(headshape.pos(:,1:2)),headshape.pos(:,3));
% headshape.pos(:,2) = headshape.pos(:,2).*-1;
% Get indices of facial points (up to 4cm above nasion)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Is 4cm the correct distance?
% Possibly different for child system?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
count_facialpoints = find(headshape.pos(:,3)<4);
if isempty(count_facialpoints)
disp('CANNOT FIND ANY FACIAL POINTS - COREG BY ICP MAY BE INACCURATE');
else
facialpoints = headshape.pos(count_facialpoints,:,:);
rrr = 1:4:length(facialpoints);
facialpoints = facialpoints(rrr,:); clear rrr;
end
% Remove facial points for now
headshape.pos(count_facialpoints,:) = [];
% Create mesh out of headshape downsampled to x points specified in the
% function call
cfg.numvertices = numvertices;
cfg.method = 'headshape';
cfg.headshape = headshape.pos;
mesh = ft_prepare_mesh(cfg, headshape);
% Replace the headshape info with the mesh points
headshape.pos = mesh.pos;
% Create figure for quality checking
figure; subplot(2,2,1);ft_plot_mesh(mesh); hold on;
title('Downsampled Mesh');
view(0,0);
subplot(2,2,2);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 1');
view(0,0);
subplot(2,2,3);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 2');
view(90,0);
subplot(2,2,4);ft_plot_mesh(headshape); hold on;
title('Downsampled Headshape View 3');
view(180,0);
print('headshape_quality','-dpdf');
% Add the facial info back in
headshape.pos = vertcat(headshape.pos,facialpoints);
% Add in names of the fiducials from the sensor
headshape.fid.label = {'NASION','LPA','RPA'};
% Convert fiducial points to BESA
% headshape.fid.pos = cat(2,fliplr(headshape.fid.pos(:,1:2)),headshape.fid.pos(:,3));
% headshape.fid.pos(:,2) = headshape.fid.pos(:,2).*-1;
% Plot for quality checking
figure;
ft_plot_headshape(headshape) %plot headshape
view(0,0);
print('headshape_quality2','-dpdf');
% Export filename
headshape_downsampled = headshape;
end
% Assign Weights Function
function y = assignweights(x, w)
% x is an indexing vector with the same number of arguments as w
y = w(:)';
end
end
|
github
|
Macquarie-MEG-Research/coreg-master
|
ft_transform_geometry_PFS_hacked.m
|
.m
|
coreg-master/realign_MEG_sensors/ft_transform_geometry_PFS_hacked.m
| 3,910 |
utf_8
|
9d375f780ec2a6c15b958746c75a7a24
|
function [output] = ft_transform_geometry_PFS_hacked(transform, input)
% FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to
% a structure with geometric information, for example a volume conduction model
% for the head, gradiometer of electrode structure containing EEG or MEG
% sensor positions and MEG coil orientations, a head shape or a source model.
%
% The units in which the transformation matrix is expressed are assumed to
% be the same units as the units in which the geometric object is
% expressed. Depending on the input object, the homogeneous transformation
% matrix should be limited to a rigid-body translation plus rotation
% (MEG-gradiometer array), or to a rigid-body translation plus rotation
% plus a global rescaling (volume conductor geometry).
%
% Use as
% output = ft_transform_geometry(transform, input)
%
% See also FT_WARP_APPLY, FT_HEADCOORDINATES
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_transform_geometry.m$
% flg rescaling check
allowscaling = ~ft_senstype(input, 'meg');
% determine the rotation matrix
rotation = eye(4);
rotation(1:3,1:3) = transform(1:3,1:3);
if any(abs(transform(4,:)-[0 0 0 1])>100*eps)
error('invalid transformation matrix');
end
%%### get rid of this accuracy checking below as some of the transformation
%%matricies will be a bit hairy###
if ~allowscaling
% allow for some numerical imprecision
%if abs(det(rotation)-1)>1e-6%100*eps
%if abs(det(rotation)-1)>100*eps % allow for some numerical imprecision
%error('only a rigid body transformation without rescaling is allowed');
%end
end
if allowscaling
% FIXME build in a check for uniform rescaling probably do svd or so
% FIXME insert check for nonuniform scaling, should give an error
end
tfields = {'pos' 'pnt' 'o' 'coilpos' 'chanpos' 'chanposold' 'chanposorg' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation
rfields = {'ori' 'nrm' 'coilori' 'chanori' 'chanoriold' 'chanoriorg'}; % only apply rotation
mfields = {'transform'}; % plain matrix multiplication
recfields = {'fid' 'bnd' 'orig'}; % recurse into these fields
% the field 'r' is not included here, because it applies to a volume
% conductor model, and scaling is not allowed, so r will not change.
fnames = fieldnames(input);
for k = 1:numel(fnames)
if ~isempty(input.(fnames{k}))
if any(strcmp(fnames{k}, tfields))
input.(fnames{k}) = apply(transform, input.(fnames{k}));
elseif any(strcmp(fnames{k}, rfields))
input.(fnames{k}) = apply(rotation, input.(fnames{k}));
elseif any(strcmp(fnames{k}, mfields))
input.(fnames{k}) = transform*input.(fnames{k});
elseif any(strcmp(fnames{k}, recfields))
for j = 1:numel(input.(fnames{k}))
input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j));
end
else
% do nothing
end
end
end
output = input;
end
function [new] = apply(transform, old)
old(:,4) = 1;
new = old * transform';
new = new(:,1:3);
end
|
github
|
philippboehmsturm/antx-master
|
antlink.m
|
.m
|
antx-master/antlink.m
| 902 |
utf_8
|
2a25c9eac9e7ffb28b6adb6c0dff143a
|
%% link ANT-TOOLBOX
% antlink or antlink(1) to setpath of ANT-TBX
% antlink(0) to remove path of ANT-TBX
function antlink(arg)
if exist('arg')~=1
arg=1;
end
if arg==1 %addPath
pa=pwd;
addpath(genpath(fullfile(pa,'freiburgLight', 'matlab', 'diffusion' ,'common')))
addpath(genpath(fullfile(pwd,'freiburgLight', 'matlab', 'spm8')))
addpath(genpath(fullfile(pa,'freiburgLight', 'allen')))
cd(fullfile(pa,'mritools'));
dtipath;
cd(pa)
elseif arg==0 %remove path
try
warning off
dirx=fileparts(fileparts(fileparts(which('ant.m'))));
rmpath(genpath(dirx));
disp('tom..and [ANT] removed from pathList');
cd(dirx);
end
end
%% OLDER VERSION
% pa=pwd;
% cd(fullfile(pa,'matlabToolsFreiburg'));
% setpath
%
% cd(fullfile(pa,'mritools'));
% dtipath
%
% cd(pa)
|
github
|
philippboehmsturm/antx-master
|
readBrukerRaw.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/functions/readBrukerRaw.m
| 17,313 |
utf_8
|
bc33cde79bf30225c54992aa788ff061
|
function [ data , addInfo] = readBrukerRaw(Acqp, varargin)
% function [ data , addInfo ] = readBrukerRaw(Acqp, [path_to_DataFile], ['specified_NRs', NR_array],
% ['specified_Jobs', job_array], ['precision', precision_string])
% Input:
% Acqp (struct): An acqp struct as generated by the function readBrukerParamFile('path/acqp')
%
% Optional inputs:
%
% path_to_dataFile (string): path to fid-data including the file name (fid or rawdata.job0)
%
% 'specified_NRs', NR_array: If you are using a standard fid file, you can specify a list of NRs
% to be read, NR starting with 1
% 'specified_NRs',[2 5 7] -> only NR 2, 5 and 7 are read
%
% 'specified_Jobs', job_array: If you are using jobs in your acquisition, you can specify
% a list of jobs you want to read, the first job is job0. If you
% want to read only the fid-file and no job, you can use
% 'specified_Jobs',[ -1 ]
%
% 'precision', precision_string: You can define the precision of the imported data:
% 'single' or 'double' (default). Single precision uses 4 bytes to
% represent a (real) floating point number, 'double' uses 8 bytes.
%
% Output:
% data: - If path_to_dataFile contains only an fid file, data is a 3D Matrix in a cell
% with dimensions (Scanvalues, NumberOfScans, Channel)
% - If path_to_dataFile contains only job files, data will be a cell array {Job0, Job1, Job2, ...},
% in which job is a 3D Matrix with dimensions (Channel, Scanvalues, NumberOfScans)
% - If path_to_dataFile contains an fid and job files, data will be a cell
% array {fidFile, Job1, Job2, ...}
%
% addInfo (struct) contains information about the selected receivers, specified NRs or specified jobs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2013
% Bruker BioSpin MRI GmbH
% D-76275 Ettlingen, Germany
%
% All Rights Reserved
%
% $Id: readBrukerRaw.m,v 1.2.4.1 2014/05/23 08:43:51 haas Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%----------------------------------------------------------------
%% Define default-value if necesseary:
% Set Parameters of InputParser (Matlab-function)
[varargin, specified_NRs]=bruker_addParamValue(varargin, 'specified_NRs', '@(x) isnumeric(x)', []);
[varargin, specified_Jobs]=bruker_addParamValue(varargin, 'specified_Jobs', '@(x) isnumeric(x)', []);
[varargin, precision]=bruker_addParamValue(varargin, 'precision', '@(x) (strcmpi(x,''double'') || strcmpi(x,''single''))', 'double');
if length(varargin) == 1
path_to_dataFile=varargin{1};
elseif isempty(varargin)
path_to_dataFile=[filesep, 'fid'];
else
warning('MATLAB:bruker_warning', 'Check your input arguments of function readBrukerRaw')
end
%----------------------------------------------------------------
%% Check for missing variables in structs:
cellstruct{1}=Acqp;
all_here = bruker_requires(cellstruct, {{'Acqp','GO_raw_data_format','BYTORDA','NI','NR','ACQ_size','GO_data_save','GO_block_size', 'AQ_mod'}});
if isfield(Acqp, 'ACQ_jobs_size')
all_here = bruker_requires(cellstruct, {{'Acqp','ACQ_jobs','ACQ_jobs_size'}}) & all_here;
end
clear cellstruct;
if ~all_here
error('Some parameters are missing');
end
%----------------------------------------------------------------
%% copy necessary parameters from inputstructs\
% under this section, the Acqp-struct is not used !
% makes it easier to find failing parameters for users
GO_raw_data_format=Acqp.GO_raw_data_format;
BYTORDA=Acqp.BYTORDA;
AQ_mod=Acqp.AQ_mod;
% Determining number of selected receive channels
numSelectedReceivers = bruker_getSelectedReceivers(Acqp);
addInfo.numSelectedReceivers=numSelectedReceivers;
if ~isempty(specified_NRs)
addInfo.specified_NRs=specified_NRs;
end
if ~isempty(specified_Jobs)
addInfo.specified_Jobs=specified_Jobs;
end
%saving the variables to an struct to make function-calls shorter
paramStruct.NI=Acqp.NI;
paramStruct.NR=Acqp.NR;
paramStruct.ACQ_size=Acqp.ACQ_size;
paramStruct.GO_data_save=Acqp.GO_data_save;
paramStruct.GO_block_size=Acqp.GO_block_size;
% If Jobs copy variables:
if isfield(Acqp, 'ACQ_jobs_size') && Acqp.ACQ_jobs_size>0
jobsExist=true;
ACQ_jobs=Acqp.ACQ_jobs;
ACQ_jobs_size=Acqp.ACQ_jobs_size;
paramStruct.ACQ_jobs=Acqp.ACQ_jobs;
paramStruct.ACQ_jobs_size=ACQ_jobs_size;
else
jobsExist=false;
end
%----------------------------------------------------------------------
%% Transform Variables from Acqp-Struct to Matlab readable:
%transform the Number-Format to Matlab-format (=format) and save the
%number of bits per value
switch(GO_raw_data_format)
case ('GO_32BIT_SGN_INT')
format='int32';
bits=32;
case ('GO_16BIT_SGN_INT')
format='int16';
bits=16;
case ('GO_32BIT_FLOAT')
format='float32';
bits=32;
otherwise
format='int32';
disp('Data-Format not correct specified! Set to int32')
bits=32;
end
%transform the machinecode-format to matlab-format (=endian)
switch(BYTORDA)
case ('little')
endian='l';
case ('big')
endian='b';
otherwise
endian='l';
disp('MacineCode-Format not correct specified! Set to little-endian')
end
% decide if RawFile is complex or real:
switch AQ_mod
case ('qf')
isComplexRaw=false;
case ('qseq')
isComplexRaw=true;
case ('qsim')
isComplexRaw=true;
case ('qdig')
isComplexRaw=true;
otherwise
error('The value of parameter AQ_mod is not supported');
end
%----------------------------------------------------------------------
%% Choose the right function(s) for reading:
if ~jobsExist % Parameter doesn's exist
% 'normal' read of fid-File:
[ data{1} ] = readfidFile(paramStruct, path_to_dataFile, isComplexRaw, specified_NRs, precision,format,bits, endian,numSelectedReceivers);
elseif (ACQ_jobs(1,1)==0) % if ScanSize entry of First job=0 -> 'normal' read of fid-File:
[ data{1} ] = readfidFile(paramStruct, path_to_dataFile, isComplexRaw, [], precision,format,bits, endian,numSelectedReceivers);
% special case: first job=normal fidFile, but there are more jobs
% ACQ_jobs_size>=2 => also jobs in this acquisition
% if length(specified_Jobs)==1 -> if specified_Jobs(1) is not -1 (-1=read no jobs) => start reading
% if length(specified_Jobs)==1 => start reading
if (ACQ_jobs_size>=2) && ( ( length(specified_Jobs)==1 && ~(specified_Jobs(1)==-1 ) || ~length(specified_Jobs)==1 ))
if isempty(specified_Jobs) % if no jobs specified: choose all jobs (without job0)
specified_Jobs=[1:ACQ_jobs_size-1];
else
specified_Jobs( (specified_Jobs==0) ) = []; % delete the zero-job if an fidFile exist and the user specified an
end
[ JobsCell ] = readJobFiles(paramStruct, path_to_dataFile, isComplexRaw, specified_Jobs, precision,format,bits, endian,numSelectedReceivers); %=Jobstruct
data{2:length(JobsCell)} = JobsCell{2:end}; % in this case: JobsCell{1}==[]
clear JobsCell;
end
% ~(ACQ_jobs(1,1)==0 => only jobs in this acquisition
% if length(specified_Jobs)==1 -> if specified_Jobs(1) is not -1 (-1=read no jobs) => start reading
% if length(specified_Jobs)==1 => start reading
elseif (~(ACQ_jobs(1,1)==0)) && ( ( length(specified_Jobs)==1 && ~(specified_Jobs(1)==-1 ) || ~length(specified_Jobs)==1 ))
[ data ] = readJobFiles(paramStruct, path_to_dataFile, isComplexRaw, specified_Jobs, precision,format,bits, endian,numSelectedReceivers);
else
error('Your AcqpFile has an unallowed job-description, or you specification was not correct');
end
end
function [ fidFile ] = readfidFile(paramStruct, path_to_dataFile, isComplexRaw, specified_NR, precision,format,bits, endian,numSelectedReceivers)
% check if specified_NR came with input -> set a boolean
if(isempty(specified_NR))
isNR_specified=false;
else
isNR_specified=true;
end
%path_to_dataFile=[path_to_dataFile, '/fid'];
% check the value of precision and change it to a boolean
if(strcmpi('double',precision))
single_bool=false;
elseif(strcmpi('single',precision))
single_bool=true;
else
single_bool=false;
disp('Your precision-input is not correct! Set to double');
end
clear('input', 'precision');
% %----------------------------------------------------------------
%% Failure Check: is data stored?
% check if acqp-parameter is st correctly
if(strcmpi(paramStruct.GO_data_save,'no'))
error('myApp:argChk','You didn''t stored your acqusition! Please change the parameters in ParaVision to save it.');
end
%----------------------------------------------------------------
%% Transform Variables from paramStruct-Struct to Matlab readable:
% shorter variable-names:
NI=paramStruct.NI;
NR=paramStruct.NR;
ACQ_size=paramStruct.ACQ_size;
% Calculating number of elements in higher dimensions
numDataHighDim=prod(paramStruct.ACQ_size(2:end));
% Calculating block size (non-complex)
if strcmp(paramStruct.GO_block_size,'Standard_KBlock_Format')
blockSize = ceil(ACQ_size(1)*numSelectedReceivers*(bits/8)/1024)*1024/(bits/8);
else
blockSize = ACQ_size(1)*numSelectedReceivers;
end
%----------------------------------------------------------------
%% Read Process:
% open file
try
fileID = fopen(path_to_dataFile,'r');
catch
fileID = -1;
end
if fileID == -1
error('Cannot open parameter file. Problem opening file %s.',path_to_dataFile);
end
% check if specific NR's are choosen:
if isNR_specified
%% Special case: read only an specified array of NRs:
%check if maximum user-selected NR > real NR or if it is an bad
%value
if (max(specified_NR)>NR || min(specified_NR) < 1 )
error('Your selected NR is to high or to low. Don''t forget the smallest value is 1. -> function abort !');
end
% reconfigure NR (for errorcheck and sorting later):
NR=length(specified_NR); % (don't save to acqp)
%calculate Size of ONE NR, defined as: blockSize * ACQ_sizes-starting-by-dim2 * NI
size_NR=blockSize*numDataHighDim*NI;
%calculate matrix-dimensions of ONE NR non-komplex:
num_columns=numDataHighDim*NI; %Spalten
num_rows=blockSize; %Zeilen
% Read process:
%--------------
%Init:
if single_bool
fidFile=zeros( num_rows, length(specified_NR)*num_columns, 'single'); % fidFile=temporary variable for fidFile
else
fidFile=zeros( num_rows, length(specified_NR)*num_columns); % fidFile=temporary variable for fidFile
end
% read th specified NR-Data:
for i=1:length(specified_NR)
% set position in file:
fseek(fileID, ( specified_NR(i)-1 )*size_NR*bits/8 , 'bof');
%read only one NR with single or double precision:
if(single_bool)
Xzw=single(fread(fileID, [num_rows, num_columns], [format, '=>single'], 0 , endian));
else
Xzw=fread(fileID, [num_rows, num_columns], format, 0 , endian);
end
% write to the output-variable:
fidFile(:,(i-1)*num_columns+1:i*num_columns)=Xzw(1:end,:);
end
else
%% normal-case: read complete fid-file
%read File to Variable fidFile with fread() and make it single-precission with single():
% Attention: Matlab ACQ_size(1) = ACQ_size(0)
if(single_bool)
fidFile=( fread(fileID, [blockSize, numDataHighDim*NI*NR], [format, '=>single'], 0, endian) );
else
fidFile=fread(fileID, [blockSize, numDataHighDim*NI*NR], format, 0, endian);
end
end
% file close
fclose(fileID);
%% short errorcheck and cut the zeros
fidFileSize=numel(fidFile);
if ~(fidFileSize==blockSize*numDataHighDim*NI*NR)
error('Size of fid file does not match parameters.');
end
fidFile=reshape(fidFile,blockSize,numDataHighDim*NI*NR); % in most cases unnecessary
% for faster execution: minimize usage of the permute-command
if blockSize ~= ACQ_size(1)*numSelectedReceivers %remove zero-lines
fidFile=permute(fidFile,[2,1]); %for faster memory access during 2 following operations
fidFile=fidFile(:,1:ACQ_size(1)*numSelectedReceivers);
% select channels for new dimension:
fidFile=reshape(fidFile,[numDataHighDim*NI*NR, ACQ_size(1) ,numSelectedReceivers]);
% resort dimensions
fidFile=permute(fidFile,[3,2,1]);
else
fidFile=reshape(fidFile,[ACQ_size(1), numSelectedReceivers, numDataHighDim*NI*NR]);
fidFile=permute(fidFile,[2 1 3]);
end
% Save to output variable:
if isComplexRaw
% convert to complex:
fidFile=complex(fidFile(:,1:2:end,:,:), fidFile(:,2:2:end,:,:));
% else: don't convert, only save
end
end
function [ JobsCell ] = readJobFiles(paramStruct, path_to_dataFile, isComplexRaw, specified_job, precision,format,bits, endian,numSelectedReceivers)
% specified_jobs or empty entry:
if(isempty(specified_job))
jobs=[0:paramStruct.ACQ_jobs_size-1];
else
jobs=specified_job;
end
clear specified_job;
if max(jobs)>paramStruct.ACQ_jobs_size-1 || min(jobs)<0
error('Your specified jobs are not correct !')
end
% check the value of precision and change it to a boolean
if(strcmpi('double',precision))
single_bool=false;
elseif(strcmpi('single',precision))
single_bool=true;
else
single_bool=false;
disp('Your precision input is not correct! Set to double');
end
clear('input', 'precision');
% %----------------------------------------------------------------
%% Failure Check: is data stored?
% check if acqp-parameter is st correctly
if(strcmpi(paramStruct.GO_data_save,'no'))
error('myApp:argChk','You didn''t store your acqusition! Please change the parameters in ParaVision to save it.');
end
%----------------------------------------------------------------
%% read jobs:
for i=jobs
% Modify path: before '../yourpath/fid'
pos=strfind(path_to_dataFile, filesep); % last '/' is end of directory description
path_to_dataFile=path_to_dataFile(1:pos(end)); % -> after: '../yourpath/'
temppath_to_dataFile=[path_to_dataFile, 'rawdata.job', num2str(i)];
%% Read Process:
% open file
try
fileID = fopen(temppath_to_dataFile,'r');
catch
fileID = -1;
end
if fileID == -1
error('Cannot open parameter file. Problem opening file %s.',temppath_to_dataFile);
end
%read File to Variable X with fread() and make it single-precission with single():
% Attention: Matlab ACQ_size(1) = ACQ_size(0)
if(single_bool)
X=( fread(fileID, [numSelectedReceivers*paramStruct.ACQ_jobs(1,i+1), inf], [format, '=>single'], 0, endian) );
else
X=fread(fileID, [numSelectedReceivers*paramStruct.ACQ_jobs(1,i+1), inf], format, 0, endian);
end
dim1=numel(X) / (paramStruct.ACQ_jobs(1,i+1)*numSelectedReceivers);
X=reshape(X,[numSelectedReceivers, paramStruct.ACQ_jobs(1,i+1),dim1]);
% % select channels for new dimension:
% dim1=numel(X) / (paramStruct.ACQ_jobs(1,i+1)*numSelectedReceivers); % = equal to numDataHighDim*NI*NR
% X=reshape(X,[dim1, paramStruct.ACQ_jobs(1,i+1), numSelectedReceivers]);
%
% % resort dimensions
% X=permute(X,[2,1,3]);
% Save to output variable:
if isComplexRaw
% convert to complex:
X=complex(X(:,1:2:end,:), X(:,2:2:end,:));
% else: don't convert, only save
end
% file close
fclose(fileID);
% Add to struct:
JobsCell{i+1}=X;
end
end
|
github
|
philippboehmsturm/antx-master
|
brViewer.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/functions/brViewer.m
| 42,785 |
utf_8
|
bffb4921f9d4903346f799e32482a19d
|
function f2=brViewer( dataset, varargin)
% f2=brViewer( dataset, ['figuretitle', 'yourfigurename'], ['imscale', imscale], ['res_factor', res_factor])
% dataset : in kSpace with sizes:
% (dim1, dim2, dim3, NumberOfObjects, NumberOfRepetitions, NumberOfChannels)
% OR
% as image with sizes:
% (dim1, dim2, dim3, NumberOfVisuFrames)
% imscale : scale image using imagesc(), e.g. imscale=double(threshold_min, threshold_max)
%
% res_factor : scalar, multiplication-factor on the imageresolution for saving as tiff
% e.g. res_factor=2 and image (256x128) -> saved tiff has (512x256) pixel. Advantage: rendering with opengl
% default value is set to 2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2012
% Bruker BioSpin MRI GmbH
% D-76275 Ettlingen, Germany
%
% All Rights Reserved
%
% $Id: brViewer.m,v 1.2.4.1 2014/05/23 08:43:51 haas Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generating invisible mainfigure - required for return value f2
fig_pos=[0 0 1130 700];
f2=figure('Visible','off','Units','pixels','Position',fig_pos,...
'WindowButtonDownFcn',{@f_WindowButtonMotionFcn});
%% Define variables for nested-function-namespace:
abs_axes=[]; axes_size=[]; line_axes=[];
n1=[]; n2=[]; n3=[]; n4=[]; n5=[]; n6=[]; n7=[]; n8=[];
axes_show=[]; actDim1=[]; actDim2=[]; actDim3=[]; actDim4=[]; actDim5=[]; actDim6=[]; actDim7=[]; actDim8=[];
cmap=[]; freq=[]; mysize=[]; tiffnumber=[]; tiffname=[]; tiffnumber_text=[]; path_text=[];
axes_handle=[]; pt=[]; ds=[];
threshold_min=[]; threshold_max=[];
save_with_colorbar=[];
%=[]; Gui-Handel
pos_group_updownfields=[]; pos_updownfields=[]; updownfields=[];
cmap_pos=[]; group_cmap=[]; cmap_colorgray=[]; cmap_gray=[]; cmap_jet=[];
complex_pos=[]; group_complex=[]; complex_abs=[]; complex_phase=[]; complex_real=[]; complex_imag=[];
scaling_pos=[]; group_size=[]; size_image=[]; size_normal=[];
group_xscale=[]; xscale_pos=[]; x_dim1=[]; x_dim2=[]; x_dim3=[]; x_dim4=[]; x_dim5=[]; x_dim6=[]; x_dim7=[]; x_dim8=[]; x_dim=[];
group_yscale=[]; yscale_pos=[]; y_dim1=[]; y_dim2=[]; y_dim3=[]; y_dim4=[]; y_dim5=[]; y_dim6=[]; y_dim7=[]; y_dim8=[]; y_none=[]; y_dim=[];
threshold_min_heading=[]; threshold_min_text=[]; threshold_max_heading=[]; threshold_max_text=[]; threshold_pos=[];
line_pos=[]; group_line=[]; linex_axes=[]; liney_axes=[]; line_value=[]; line_text=[];
path_pos=[]; path_button=[]; tiffnumber_heading=[]; tiff_button=[]; tiff_colorbar_pos=[]; group_tiff_colorbar=[]; tiff_colorbar_on=[]; tiff_colorbar_off=[];
%% Read arguments
[varargin, figuretitle ] = bruker_addParamValue( varargin, 'figuretitle', '@(x) ischar(x)', 'DataViewer');
[varargin, imscale ] = bruker_addParamValue( varargin, 'imscale', '@(x) 1', []);
[varargin, res_factor ] = bruker_addParamValue( varargin, 'res_factor', '@(x) isscalar', 2);
imagescale=imscale;
clear varargin;
if ~exist('dataset', 'var') || ~isnumeric(dataset)
error('dataset has to be exist and to be numeric.');
end
gui_setup;
% End main-function
% end is at the end of the file because of nested functions
%-----------------------------------------------------------------------------------------------------------------------------------------------------
%% Gui setup
function gui_setup(source, eventdata)
%% Setup
figure(f2);
set(f2, 'Visible', 'on', 'ResizeFcn',@figResize)
% reduce number of dimensions to 5 if necessary
dims=size(dataset);
if length(dims)>8
dataset=reshape(dataset,[size(dataset,1), size(dataset,2), size(dataset,3), size(dataset,4), prod(dims(5:end))]);
end
% Generating axes (=image-field)
axes_size=[200,170,500,500];
abs_axes=axes('Units','pixels','Position',axes_size);
line_axes=[axes_size(1)+axes_size(3)+60,fig_pos(4)-10-500,350,500];
% Generate controls:
gen_controls; % Function-call
%% Initialize data
[n1,n2,n3,n4,n5,n6,n7,n8] = size(dataset);
% Initialize objects
axes_show=[1 2]; % choose the dimensions shown at startup: axes_show(1)=Dimension auf x-Achse, axes_show(2)=Dimension auf y-Achse,
dims=ones(8,1); % exclude 1st and 2nd dim
for i=1:8
if size(dataset,i) >1
set(updownfields.text{i},'Visible', 'on');
set(updownfields.heading{i},'Visible', 'on');
set(updownfields.up{i}, 'Visible', 'on');
set(updownfields.down{i}, 'Visible', 'on');
set(x_dim{i}, 'visible', 'on');
set(y_dim{i}, 'visible', 'on');
dims(i)=ceil(size(dataset,i)/2);
end
end
actDim1=size(dataset,1);
actDim2=size(dataset,2);
actDim3=dims(3);
actDim4=dims(4);
actDim5=dims(5);
actDim6=dims(6);
actDim7=dims(7);
actDim8=dims(8);
set(updownfields.text{1},'String',int2str(actDim1));
set(updownfields.text{2},'String',int2str(actDim2));
set(updownfields.text{3},'String',int2str(actDim3));
set(updownfields.text{4},'String',int2str(actDim4));
set(updownfields.text{5},'String',int2str(actDim5));
set(updownfields.text{6},'String',int2str(actDim6));
set(updownfields.text{7},'String',int2str(actDim7));
set(updownfields.text{8},'String',int2str(actDim8));
set(updownfields.heading{1},'String','Dim-1');
set(updownfields.heading{2},'String','Dim-2');
set(updownfields.heading{3},'String','Dim-3');
set(updownfields.heading{4},'String','Dim-4');
set(updownfields.heading{5},'String','Dim-5');
set(updownfields.heading{6},'String','Dim-6');
set(updownfields.heading{7},'String','Dim-7');
set(updownfields.heading{8},'String','Dim-8');
% disable used dimensions
if axes_show(1)~=0 % normal:
for i=axes_show
set(updownfields.text{i},'Visible', 'off');
set(updownfields.up{i}, 'Visible', 'off');
set(updownfields.down{i}, 'Visible', 'off');
end
else % none:
set(updownfields.text{axes_show(2)},'Visible', 'off');
set(updownfields.up{axes_show(2)}, 'Visible', 'off');
set(updownfields.down{axes_show(2)}, 'Visible', 'off');
end
cmap='bruker_ColorGray';
freq='abs';
mysize='image';
tiffnumber=1;
tiffname=['.', filesep, 'Image'];
set(tiffnumber_text,'String',int2str(tiffnumber));
set(path_text, 'String',['next save: ', tiffname, num2str(tiffnumber), '.tiff']);
%save_with_colorbar=false;
set(f2,'Position', fig_pos);
% Global appearance settings
movegui(f2,'center');
set(f2,'Name',figuretitle);
set(f2,'Visible','on');
ds=dataset(1:actDim1,1:actDim2,actDim3, actDim4, actDim5, actDim6, actDim7, actDim8);
% for line plot
axes_handle=abs_axes;
pt=[ceil(n2/2) ceil(n1/2)];
Draw_Image(false);
Draw_Line(false);
end
%% Generating controls for frame selection
function gen_controls
% Generate 5 invisible up-down-text-fields:
pos_group_updownfields=[10 20; 105 20; 200 20; 295 20; 390 20; 485 20; 580 20; 675 20];
for i=1:8
pos_updownfields.heading{i}=[pos_group_updownfields(i,1) pos_group_updownfields(i,2)+40 60 15];
pos_updownfields.text{i}=[pos_group_updownfields(i,1) pos_group_updownfields(i,2) 60 30];
pos_updownfields.up{i}=[pos_group_updownfields(i,1)+65 pos_group_updownfields(i,2)+15 15 15];
pos_updownfields.down{i}=[pos_group_updownfields(i,1)+65 pos_group_updownfields(i,2) 15 15];
updownfields.heading{i}=uicontrol('Style','text',...
'Position',pos_updownfields.heading{i},'Visible','off');
updownfields.text{i} = uicontrol('Style','edit',...
'Position',pos_updownfields.text{i},'Visible','off');
updownfields.up{i} = uicontrol('Style','pushbutton','String','+',...
'Position',pos_updownfields.up{i},'Visible','off');
updownfields.down{i} = uicontrol('Style','pushbutton','String','-',...
'Position',pos_updownfields.down{i},'Visible','off');
end
set(updownfields.text{1},'Callback', {@updownfield_text_1_Callback});
set(updownfields.text{2},'Callback', {@updownfield_text_2_Callback});
set(updownfields.text{3},'Callback', {@updownfield_text_3_Callback});
set(updownfields.text{4},'Callback', {@updownfield_text_4_Callback});
set(updownfields.text{5},'Callback', {@updownfield_text_5_Callback});
set(updownfields.text{6},'Callback', {@updownfield_text_6_Callback});
set(updownfields.text{7},'Callback', {@updownfield_text_7_Callback});
set(updownfields.text{8},'Callback', {@updownfield_text_8_Callback});
set(updownfields.up{1},'Callback', {@updownfield_up_1_Callback});
set(updownfields.up{2},'Callback', {@updownfield_up_2_Callback});
set(updownfields.up{3},'Callback', {@updownfield_up_3_Callback});
set(updownfields.up{4},'Callback', {@updownfield_up_4_Callback});
set(updownfields.up{5},'Callback', {@updownfield_up_5_Callback});
set(updownfields.up{6},'Callback', {@updownfield_up_6_Callback});
set(updownfields.up{7},'Callback', {@updownfield_up_7_Callback});
set(updownfields.up{8},'Callback', {@updownfield_up_8_Callback});
set(updownfields.down{1},'Callback', {@updownfield_down_1_Callback});
set(updownfields.down{2},'Callback', {@updownfield_down_2_Callback});
set(updownfields.down{3},'Callback', {@updownfield_down_3_Callback});
set(updownfields.down{4},'Callback', {@updownfield_down_4_Callback});
set(updownfields.down{5},'Callback', {@updownfield_down_5_Callback});
set(updownfields.down{6},'Callback', {@updownfield_down_6_Callback});
set(updownfields.down{7},'Callback', {@updownfield_down_7_Callback});
set(updownfields.down{8},'Callback', {@updownfield_down_8_Callback});
% create buttons for choosing x-axes
xscale_pos=[axes_size(1)-10 axes_size(2)-90 axes_size(3)+65 40; ...
10 5 60 20;...
80 5 60 20; ...
150 5 60 20;...
220 5 60 20; ...
290 5 60 20; ...
360 5 60 20; ...
420 5 60 20; ...
490 5 60 20];
group_xscale = uibuttongroup('visible','on','Title','X-Axis','Units',...
'pixels','Position',xscale_pos(1,:));
x_dim{1} = uicontrol('Style','Radio','String','dim1',...
'pos',xscale_pos(2,:),'parent',group_xscale,'visible', 'off');
x_dim{2} = uicontrol('Style','Radio','String','dim2',...
'pos',xscale_pos(3,:),'parent',group_xscale,'visible', 'off');
x_dim{3} = uicontrol('Style','Radio','String','dim3',...
'pos',xscale_pos(4,:),'parent',group_xscale,'visible', 'off');
x_dim{4} = uicontrol('Style','Radio','String','dim4',...
'pos',xscale_pos(5,:),'parent',group_xscale,'visible', 'off');
x_dim{5} = uicontrol('Style','Radio','String','dim5',...
'pos',xscale_pos(6,:),'parent',group_xscale,'visible', 'off');
x_dim{6} = uicontrol('Style','Radio','String','dim6',...
'pos',xscale_pos(7,:),'parent',group_xscale,'visible', 'off');
x_dim{7} = uicontrol('Style','Radio','String','dim7',...
'pos',xscale_pos(8,:),'parent',group_xscale,'visible', 'off');
x_dim{8} = uicontrol('Style','Radio','String','dim8',...
'pos',xscale_pos(9,:),'parent',group_xscale,'visible', 'off');
set(group_xscale,'SelectionChangeFcn',@group_xscale_SelectionChangeFcn);
set(group_xscale,'SelectedObject',x_dim{1});
set(group_xscale,'Visible','on');
% create buttons for choosing y-axes
yscale_pos=[axes_size(1)-90 axes_size(2)+axes_size(4)-300 60 300];
yscale_pos(2:10,:)=[2 yscale_pos(1,4)-50 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-80 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-110 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-140 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-170 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-200 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-230 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-260 yscale_pos(1,3)-4 20; ...
2 yscale_pos(1,4)-290 yscale_pos(1,3)-4 20];
group_yscale = uibuttongroup('visible','off','Title','Y-Axis','Units',...
'pixels','Position',yscale_pos(1,:));
y_dim{1} = uicontrol('Style','Radio','String','dim1',...
'pos',yscale_pos(2,:),'parent',group_yscale,'visible', 'off');
y_dim{2} = uicontrol('Style','Radio','String','dim2',...
'pos',yscale_pos(3,:),'parent',group_yscale,'visible', 'off');
y_dim{3} = uicontrol('Style','Radio','String','dim3',...
'pos',yscale_pos(4,:),'parent',group_yscale,'visible', 'off');
y_dim{4} = uicontrol('Style','Radio','String','dim4',...
'pos',yscale_pos(5,:),'parent',group_yscale,'visible', 'off');
y_dim{5} = uicontrol('Style','Radio','String','dim5',...
'pos',yscale_pos(6,:),'parent',group_yscale,'visible', 'off');
y_dim{6} = uicontrol('Style','Radio','String','dim6',...
'pos',yscale_pos(7,:),'parent',group_yscale,'visible', 'off');
y_dim{7} = uicontrol('Style','Radio','String','dim7',...
'pos',yscale_pos(8,:),'parent',group_yscale,'visible', 'off');
y_dim{8} = uicontrol('Style','Radio','String','dim8',...
'pos',yscale_pos(9,:),'parent',group_yscale,'visible', 'off');
y_none = uicontrol('Style','Radio','String','none',...
'pos',yscale_pos(10,:),'parent',group_yscale,'visible', 'on');
set(group_yscale,'SelectionChangeFcn',@group_yscale_SelectionChangeFcn);
set(group_yscale,'SelectedObject',y_dim{2});
set(group_yscale,'Visible','on');
% IF Frequency -> activate this box with: real, imag, abs, phase
complex_pos=[10 sum(yscale_pos(1,[2,4]))-120 85 120; 3 80 75 20; 3 55 75 20; 3 30 75 20; 3 5 75 20];
group_complex = uibuttongroup('visible','off','Title','Mode','Units',...
'pixels','Position',complex_pos(1,:));
complex_abs = uicontrol('Style','Radio','String','absolute',...
'pos',complex_pos(2,:),'parent',group_complex,'HandleVisibility','off');
complex_phase = uicontrol('Style','Radio','String','phase',...
'pos',complex_pos(3,:),'parent',group_complex,'HandleVisibility','off');
complex_real = uicontrol('Style','Radio','String','real',...
'pos',complex_pos(4,:),'parent',group_complex,'HandleVisibility','off');
complex_imag = uicontrol('Style','Radio','String','imag',...
'pos',complex_pos(5,:),'parent',group_complex,'HandleVisibility','off');
set(group_complex,'SelectionChangeFcn',@group_complex_SelectionChangeFcn);
set(group_complex,'SelectedObject',complex_abs);
set(group_complex,'Visible','on');
% threshold:
threshold_pos=[complex_pos(1,1), complex_pos(1,2)-30-15, complex_pos(1,3), 30];
threshold_pos(2:4,1:4)=[threshold_pos(1,1), threshold_pos(1,2)-35, threshold_pos(1,3), threshold_pos(1,4);...
threshold_pos(1,1), threshold_pos(1,2)-80, threshold_pos(1,3), threshold_pos(1,4);...
threshold_pos(1,1), threshold_pos(1,2)-115, threshold_pos(1,3), threshold_pos(1,4)];
threshold_min_heading = uicontrol('Style','text','String','Threshold min:',...
'Position',threshold_pos(1,:));
threshold_min_text = uicontrol('Style','edit',...
'Position',threshold_pos(2,:),'Callback',{@threshold_min_text_Callback}, 'FontSize', 8);
threshold_max_heading = uicontrol('Style','text','String','Threshold max:',...
'Position',threshold_pos(3,:));
threshold_max_text = uicontrol('Style','edit',...
'Position',threshold_pos(4,:),'Callback',{@threshold_max_text_Callback}, 'FontSize', 8);
% Create controls for scaling
scaling_pos=[10 yscale_pos(1,2)-95-15 yscale_pos(1,1)+yscale_pos(1,3)-10 95; 10 55 130 20; 10 30 130 20];
group_size = uibuttongroup('visible','off','Title','Image size','Units',...
'pixels','Position',scaling_pos(1,:));
size_image = uicontrol('Style','Radio','String','Square Pixels',...
'pos',scaling_pos(2,:),'parent',group_size,'HandleVisibility','off');
size_normal = uicontrol('Style','Radio','String','Fullsize',...
'pos',scaling_pos(3,:),'parent',group_size,'HandleVisibility','off');
set(group_size,'SelectionChangeFcn',@group_size_SelectionChangeFcn);
set(group_size,'SelectedObject',size_image);
set(group_size,'Visible','on');
% Create controls for colormap and scaling
cmap_pos=[10 scaling_pos(1,2)-95-15 scaling_pos(1,3) 95; 10 55 90 20; 10 30 80 20; 10 5 80 20];
group_cmap = uibuttongroup('visible','off','Title','Colormap','Units',...
'pixels','Position',cmap_pos(1,:));
cmap_colorgray = uicontrol('Style','Radio','String','ColorGray',...
'pos',cmap_pos(2,:),'parent',group_cmap,'HandleVisibility','off');
cmap_gray = uicontrol('Style','Radio','String','Gray',...
'pos',cmap_pos(3,:),'parent',group_cmap,'HandleVisibility','off');
cmap_jet = uicontrol('Style','Radio','String','Jet',...
'pos',cmap_pos(4,:),'parent',group_cmap,'HandleVisibility','off');
set(group_cmap,'SelectionChangeFcn',@group_cmap_SelectionChangeFcn);
set(group_cmap,'SelectedObject',cmap_colorgray);
set(group_cmap,'Visible','on');
% Create controls for line plots
line_pos=[line_axes; ...
30 20, line_axes(3)-40 line_axes(4)/2-50; ...
30 line_axes(4)/2+15, line_axes(3)-40 line_axes(4)/2-50; ...
line_axes(1)+line_axes(3)/2-50 line_axes(2)-30 40 15; ...
line_axes(1)+line_axes(3)/2-10 line_axes(2)-30 60 15];
group_line=uipanel(f2,'Units','pixels','Title','Line plot', 'Position',line_pos(1,:));
linex_axes=axes('Units','pixels','Parent',group_line, 'Position',line_pos(2,:));
liney_axes=axes('Units','pixels','Parent',group_line, 'Position',line_pos(3,:));
line_value=uicontrol('Style','text','Position',line_pos(4,:), 'String','value:');
line_text=uicontrol('Style','text','Position',line_pos(5,:), 'String','');
%% Set path, name and printbutton for printing:
path_pos=[line_axes(1)+10 100 165 30];
path_pos(2:3,:)=[path_pos(1,1), path_pos(1,2)-45 line_axes(3) 35; ...
path_pos(1,1)+path_pos(1,3)+10 path_pos(1,2) 0 0]; % pos of tiffnumber
path_pos(4:6,:)=[path_pos(3,1) path_pos(3,2)+35 70 15;...
path_pos(3,1) path_pos(3,2) 70 30; ...
path_pos(1,1)+path_pos(1,3)+85 path_pos(1,2) 80 30];
path_button=uicontrol('Style','pushbutton','String','Set path and Dataname',...
'Position',path_pos(1,:),...
'Callback',{@path_button_ButtonDownFcn});
% show datapath:
path_text=uicontrol('Style','text','Position',path_pos(2,:),...
'String',['next save: .', filesep, 'Image1.tiff']);
% tiffnumber
tiffnumber_heading = uicontrol('Style','text','String','number:',...
'Position',path_pos(4,:));
tiffnumber_text = uicontrol('Style','edit',...
'Position',path_pos(5,:),'Callback',{@tiffnumber_text_Callback});
% Print to tiff
tiff_button=uicontrol('Style','pushbutton','String','Save as .tiff',...
'Position',path_pos(6,:),...
'Callback',{@tiff_button_ButtonDownFcn});
% Colarbar selector
tiff_colorbar_pos=[path_pos(1,1), path_pos(1,2)-90 line_axes(3) 40;...
10 5 150 20;...
160 5 150 20];
group_tiff_colorbar = uibuttongroup('visible','on','Title','Colorbar','Units',...
'pixels','Position',tiff_colorbar_pos(1,:));
tiff_colorbar_off = uicontrol('Style','Radio','String','save only image',...
'pos',tiff_colorbar_pos(2,:),'parent',group_tiff_colorbar,'HandleVisibility','off');
tiff_colorbar_on = uicontrol('Style','Radio','String','save with colorbar',...
'pos',tiff_colorbar_pos(3,:),'parent',group_tiff_colorbar,'HandleVisibility','off');
set(group_tiff_colorbar,'SelectionChangeFcn',@group_tiff_colorbar_SelectionChangeFcn);
set(group_tiff_colorbar,'SelectedObject',tiff_colorbar_off);
set(group_tiff_colorbar,'Visible','on');
end
%% Figure resize function
function figResize(src,evt)
fpos = get(f2,'Position');
for i=1:8
set(updownfields.heading{i}, 'Position', posScal(pos_updownfields.heading{i}));
set(updownfields.text{i}, 'Position', posScal(pos_updownfields.text{i}));
set(updownfields.up{i}, 'Position', posScal(pos_updownfields.up{i}));
set(updownfields.down{i}, 'Position', posScal(pos_updownfields.down{i}));
end
set(group_cmap, 'Position', posScal(cmap_pos(1,:)));
set(cmap_colorgray, 'pos', posScal(cmap_pos(2,:)));
set(cmap_gray, 'pos', posScal(cmap_pos(3,:)));
set(cmap_jet, 'pos', posScal(cmap_pos(4,:)));
set(group_complex, 'Position',posScal(complex_pos(1,:)));
set(complex_abs, 'pos',posScal(complex_pos(2,:)));
set(complex_phase, 'pos', posScal(complex_pos(3,:)));
set(complex_real, 'pos',posScal(complex_pos(4,:)));
set(complex_imag, 'pos',posScal(complex_pos(5,:)));
set(group_size, 'Position',posScal(scaling_pos(1,:)));
set(size_image, 'pos',posScal(scaling_pos(2,:)));
set(size_normal, 'pos',posScal(scaling_pos(3,:)));
set(group_xscale, 'pos', posScal(xscale_pos(1,:)));
set(x_dim1, 'pos', posScal(xscale_pos(2,:)));
set(x_dim2, 'pos', posScal(xscale_pos(3,:)));
set(x_dim3, 'pos', posScal(xscale_pos(4,:)));
set(x_dim4, 'pos', posScal(xscale_pos(5,:)));
set(x_dim5, 'pos', posScal(xscale_pos(6,:)));
set(x_dim6, 'pos', posScal(xscale_pos(7,:)));
set(x_dim7, 'pos', posScal(xscale_pos(8,:)));
set(x_dim8, 'pos', posScal(xscale_pos(9,:)));
set(group_yscale, 'pos', posScal(yscale_pos(1,:)));
set(y_dim1, 'pos', posScal(yscale_pos(2,:)));
set(y_dim2, 'pos', posScal(yscale_pos(3,:)));
set(y_dim3, 'pos', posScal(yscale_pos(4,:)));
set(y_dim4, 'pos', posScal(yscale_pos(5,:)));
set(y_dim5, 'pos', posScal(yscale_pos(6,:)));
set(y_dim6, 'pos', posScal(yscale_pos(7,:)));
set(y_dim7, 'pos', posScal(yscale_pos(8,:)));
set(y_dim8, 'pos', posScal(yscale_pos(9,:)));
set(y_none, 'pos', posScal(yscale_pos(10,:)));
set(threshold_min_heading, 'pos', posScal(threshold_pos(1,:)));
set(threshold_min_text, 'pos', posScal(threshold_pos(2,:)));
set(threshold_max_heading, 'pos', posScal(threshold_pos(3,:)));
set(threshold_max_text, 'pos', posScal(threshold_pos(4,:)));
set(group_line, 'pos', posScal(line_pos(1,:)))
set(linex_axes, 'pos', posScal(line_pos(2,:)));
set(liney_axes, 'pos', posScal(line_pos(3,:)));
set(line_value, 'pos', posScal(line_pos(4,:)));
set(line_text, 'pos', posScal(line_pos(5,:)));
set(path_button, 'pos', posScal(path_pos(1,:)));
set(path_text, 'pos', posScal(path_pos(2,:)));
set(tiffnumber_heading, 'pos', posScal(path_pos(4,:)));
set(tiffnumber_text, 'pos', posScal(path_pos(5,:)));
set(tiff_button, 'pos', posScal(path_pos(6,:)));
set(group_tiff_colorbar,'pos', posScal(tiff_colorbar_pos(1,:)));
set(tiff_colorbar_off, 'pos', posScal(tiff_colorbar_pos(2,:)));
set(tiff_colorbar_on, 'pos', posScal(tiff_colorbar_pos(3,:)));
set(abs_axes, 'Position', axes_size.*[fpos(3)/fig_pos(3) fpos(4)/fig_pos(4) fpos(3)/fig_pos(3) fpos(4)/fig_pos(4)]);
end
function [new_pos]=posScal(original_pos)
fpos = get(f2,'Position');
new_pos=[fpos(3)*original_pos(1)/fig_pos(3), fpos(4)*original_pos(2)/fig_pos(4) fpos(3)*original_pos(3)/fig_pos(3) fpos(4)*original_pos(4)/fig_pos(4)];
end
%% Callbacks
% Field 1
function updownfield_text_1_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n1)
actDim1=floor(valNum);
end
set(source,'String',int2str(actDim1));
end
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_1_Callback(source, eventdata)
if (actDim1+1<=n1)
actDim1=actDim1+1;
end
set(updownfields.text{1},'String',int2str(actDim1));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_down_1_Callback(source, eventdata)
if (actDim1-1>=1)
actDim1=actDim1-1;
end
set(updownfields.text{1},'String',int2str(actDim1));
Draw_Image(false);
Draw_Line(false);
end
% Field 2
function updownfield_text_2_Callback(source, eventdata)
if (1<=valNum) && (valNum<=n2)
actDim2=floor(valNum);
end
set(source,'String',int2str(actDim2));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_2_Callback(source, eventdata)
if (actDim2+1<=n2)
actDim2=actDim2+1;
end
set(updownfields.text{2},'String',int2str(actDim2));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_down_2_Callback(source, eventdata)
if (actDim2-1>=1)
actDim2=actDim2-1;
end
set(updownfields.text{2},'String',int2str(actDim2));
Draw_Image(false);
Draw_Line(false);
end
% Field 3
function updownfield_text_3_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n3)
actDim3=floor(valNum);
end
end
set(source,'String',int2str(actDim3));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_3_Callback(source, eventdata)
if (actDim3+1<=n3)
actDim3=actDim3+1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{3},'String',int2str(actDim3));
end
function updownfield_down_3_Callback(source, eventdata)
if (actDim3-1>=1)
actDim3=actDim3-1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{3},'String',int2str(actDim3));
end
% Field 4
function updownfield_text_4_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n4)
actDim4=floor(valNum);
end
end
set(source,'String',int2str(actDim4));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_4_Callback(source, eventdata)
if (actDim4+1<=n4)
actDim4=actDim4+1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{4},'String',int2str(actDim4));
end
function updownfield_down_4_Callback(source, eventdata)
if (actDim4-1>=1)
actDim4=actDim4-1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{4},'String',int2str(actDim4));
end
% Field 5
function updownfield_text_5_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n5)
actDim5=floor(valNum);
end
end
set(source,'String',int2str(actDim5));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_5_Callback(source, eventdata)
if (actDim5+1<=n5)
actDim5=actDim5+1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{5},'String',int2str(actDim5));
end
function updownfield_down_5_Callback(source, eventdata)
if (actDim5-1>=1)
actDim5=actDim5-1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{5},'String',int2str(actDim5));
end
% Field 6
function updownfield_text_6_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n6)
actDim6=floor(valNum);
end
end
set(source,'String',int2str(actDim6));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_6_Callback(source, eventdata)
if (actDim6+1<=n6)
actDim6=actDim6+1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{6},'String',int2str(actDim6));
end
function updownfield_down_6_Callback(source, eventdata)
if (actDim6-1>=1)
actDim6=actDim6-1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{6},'String',int2str(actDim6));
end
% Field 7
function updownfield_text_7_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n7)
actDim7=floor(valNum);
end
end
set(source,'String',int2str(actDim7));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_7_Callback(source, eventdata)
if (actDim7+1<=n7)
actDim7=actDim7+1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{7},'String',int2str(actDim7));
end
function updownfield_down_7_Callback(source, eventdata)
if (actDim7-1>=1)
actDim7=actDim7-1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{7},'String',int2str(actDim7));
end
% Field 8
function updownfield_text_8_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum))
if (1<=valNum) && (valNum<=n8)
actDim8=floor(valNum);
end
end
set(source,'String',int2str(actDim8));
Draw_Image(false);
Draw_Line(false);
end
function updownfield_up_8_Callback(source, eventdata)
if (actDim8+1<=n8)
actDim8=actDim8+1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{8},'String',int2str(actDim8));
end
function updownfield_down_8_Callback(source, eventdata)
if (actDim8-1>=1)
actDim8=actDim8-1;
Draw_Image(false);
Draw_Line(false);
end
set(updownfields.text{8},'String',int2str(actDim8));
end
% Colormap group
function group_cmap_SelectionChangeFcn(source, eventdata)
switch get(eventdata.NewValue,'String') % Get Tag of selected object
case 'ColorGray'
cmap='bruker_ColorGray';
case 'Gray'
cmap='gray';
case 'Jet'
cmap='jet';
end
Draw_Image(false);
end
% freq. mode
function group_complex_SelectionChangeFcn(source, eventdata)
switch get(eventdata.NewValue,'String') % Get Tag of selected object
case 'absolute'
freq='abs';
case 'phase'
freq='phase';
case 'real'
freq='real';
case 'imag'
freq='imag';
end
Draw_Image(false);
end
% Size group
function group_size_SelectionChangeFcn(source, eventdata)
switch get(eventdata.NewValue,'String') % Get Tag of selected object
case 'Square Pixels'
mysize='image';
case 'Fullsize'
mysize='normal';
end
Draw_Image(false);
end
% Get pointer location for line plots
function f_WindowButtonMotionFcn(source, eventdata)
% location of mouse pointer
pa=get(abs_axes,'CurrentPoint');
pa=round(pa(1:2:3));
if (pa(2)>=1 && pa(2)<=size(ds,1) && pa(1)>=1 && pa(1)<=size(ds,2)),
% pointer is on abs_axes
axes_handle=abs_axes;
pt=pa;
Draw_Image(false);
Draw_Line(true);
end
end
% xscale group
function group_xscale_SelectionChangeFcn(source, eventdata)
switch get(eventdata.NewValue,'String') % Get Tag of selected object
case 'dim1'
axes_show(1)=1;
case 'dim2'
axes_show(1)=2;
case 'dim3'
axes_show(1)=3;
case 'dim4'
axes_show(1)=4;
case 'dim5'
axes_show(1)=5;
case 'dim6'
axes_show(1)=6;
case 'dim7'
axes_show(1)=7;
case 'dim8'
axes_show(1)=8;
end
handle_dimensions;
Draw_Image(false);
Draw_Line(false);
end
% yscale group
function group_yscale_SelectionChangeFcn(source, eventdata)
switch get(eventdata.NewValue,'String') % Get Tag of selected object
case 'dim1'
axes_show(2)=1;
case 'dim2'
axes_show(2)=2;
case 'dim3'
axes_show(2)=3;
case 'dim4'
axes_show(2)=4;
case 'dim5'
axes_show(2)=5;
case 'dim6'
axes_show(2)=6;
case 'dim7'
axes_show(2)=7;
case 'dim8'
axes_show(2)=8;
case 'none'
axes_show(2)=0;
end
handle_dimensions;
Draw_Image(false);
Draw_Line(false);
end
% threshold:
function threshold_min_text_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum)) && isempty(imscale)
threshold_min=valNum;
set(source,'String',num2str(valNum, '% 10.2f'));
elseif ~isempty(imscale)
set(source,'String','');
else
set(source,'String',num2str(threshold_min, '% 10.2f'));
end
Draw_Image(true);
Draw_Line(false);
end
function threshold_max_text_Callback(source, eventdata)
valString=get(source,'String');
valNum=str2double(valString);
if (~isnan(valNum)) && isempty(imscale)
threshold_max=valNum;
set(source,'String',num2str(valNum, '% 10.2f'));
elseif ~isempty(imscale)
set(source,'String','');
else
set(source,'String',num2str(threshold_max, '% 10.2f'));
end
Draw_Image(true);
Draw_Line(false);
end
function path_button_ButtonDownFcn(source, eventdata)
tiffname=uiputfile('*', 'Save Image as');
if tiffnumber <= 0
set(path_text, 'String',['next save: ', tiffname, '.tiff']);
else
set(path_text, 'String',['next save: ', tiffname, num2str(tiffnumber), '.tiff']);
end
end
function tiffnumber_text_Callback(source, eventdata)
valString=get(source, 'String');
valNum=str2double(valString);
if (~isnan(valNum))
tiffnumber=floor(valNum);
end
set(source,'String',int2str(tiffnumber));
if tiffnumber>=1
set(path_text, 'String',['next save: ', tiffname , num2str(tiffnumber), '.tiff']);
else
set(path_text, 'String',['next save: ', tiffname, '.tiff']);
end
end
function group_tiff_colorbar_SelectionChangeFcn(source, eventdata)
switch get(eventdata.NewValue,'String') % Get Tag of selected object
case 'save only image'
save_with_colorbar=false;
case 'save with colorbar'
save_with_colorbar=true;
end
end
% save image as tiff
function tiff_button_ButtonDownFcn(source, eventdata)
% generate image:
normal_axes_handle=gca; % save handle for write-back
create_slice;
if save_with_colorbar
%% with colorbar
if axes_show(2)~=0 && strcmp(mysize, 'image')
printfigure=figure('Units','pixels','Position',[0,0,size(ds,2)+130+60, size(ds,1)+60], 'Visible', 'off');
print_axes=axes('Units','pixels','Position',[30,30,size(ds,2)+130, size(ds,1)]);
axis image;
elseif axes_show(2)~=0 && strcmp(mysize, 'normal')
printaxes_size=get(abs_axes,'Position');
printfigure=figure('Position',[0,0,printaxes_size(3)+130+60,printaxes_size(4)+60], 'Visible', 'off');
printaxes_size=[30,30,printaxes_size(3)+130,printaxes_size(4)];
print_axes=axes('Units','pixels','Position',printaxes_size);
axis normal;
end
% show image:
if axes_show(2)~=0
axes(print_axes);
colormap(cmap);
imagesc(ds,imagescale);
set(print_axes,'Tag','abs');
colorbar;
else
plot(squeeze(ds));
end
else
%% only image
if axes_show(2)~=0 && strcmp(mysize, 'image')
printfigure=figure('Visible', 'off', 'Units','pixels','Position',[0,0,size(ds,2), size(ds,1)]);
print_axes=axes('Units','pixels','Position',[0,0,size(ds,2), size(ds,1)]);
axis image;
elseif axes_show(2)~=0 && strcmp(mysize, 'normal')
printaxes_size=get(abs_axes,'Position');
printfigure=figure('Visible', 'off', 'Position',[0,0,printaxes_size(3),printaxes_size(4)]);
printaxes_size=[0,0,printaxes_size(3),printaxes_size(4)];
print_axes=axes('Units','pixels','Position',printaxes_size);
axis normal;
end
% show image:
if axes_show(2)~=0
axes(print_axes);
colormap(cmap);
imagesc(ds,imagescale);
set(gca, 'XTickLabelMode', 'manual', 'XTickLabel', []); % remove numbers on X-axes
set(gca, 'YTickLabelMode', 'manual', 'YTickLabel', []); % remove numbers on Y-axes
else
plot(squeeze(ds));
end
end
% save image
if tiffnumber>=1
dataname=[tiffname, num2str(tiffnumber), '.tiff'];
else
dataname=[tiffname, '.tiff'];
end
res = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res_factor))];
set(printfigure, 'PaperPositionMode', 'auto');
print(printfigure, '-opengl', res, '-dtiff', dataname);
if tiffnumber>=1
tiffnumber=tiffnumber+1;
set(tiffnumber_text, 'String',num2str(tiffnumber));
set(path_text, 'String',['next save: ', tiffname , num2str(tiffnumber), '.tiff']);
else
set(path_text, 'String',['next save: ', tiffname, '.tiff']);
end
close(printfigure);
figure(f2);
axes(normal_axes_handle); % write handle back
end
function handle_dimensions
dims=ones(8,1); % exclude 1st and 2nd dim
for i=1:8
if size(dataset,i) >1
dims(i)=ceil(size(dataset,i)/2);
set(updownfields.text{i},'Visible', 'on', 'String', num2str(dims(i)));
set(updownfields.heading{i},'Visible', 'on');
set(updownfields.up{i}, 'Visible', 'on');
set(updownfields.down{i}, 'Visible', 'on');
end
end
actDim1=dims(1);
actDim2=dims(2);
actDim3=dims(3);
actDim4=dims(4);
actDim5=dims(5);
actDim6=dims(6);
actDim7=dims(7);
actDim8=dims(8);
if axes_show(2)~=0 % normal:
for i=axes_show
set(updownfields.text{i},'Visible', 'off');
set(updownfields.up{i}, 'Visible', 'off');
set(updownfields.down{i}, 'Visible', 'off');
end
else % none:
set(updownfields.text{axes_show(1)},'Visible', 'off');
set(updownfields.up{axes_show(1)}, 'Visible', 'off');
set(updownfields.down{axes_show(1)}, 'Visible', 'off');
end
end
%% create Slice
function create_slice
actDim_ges=[actDim1, actDim2, actDim3, actDim4, actDim5, actDim6, actDim7, actDim8];
d=cell(8,1);
for i=1:length(actDim_ges)
if i==axes_show(1) || i==axes_show(2)
d{i}=1:size(dataset,i);
else
d{i}=actDim_ges(i);
end
end
% create Image:
switch freq
case 'abs'
ds=abs(squeeze(dataset(d{1}, d{2}, d{3}, d{4}, d{5}, d{6}, d{7}, d{8})));
case 'phase'
ds=angle(squeeze(dataset(d{1}, d{2}, d{3}, d{4}, d{5}, d{6}, d{7}, d{8})));
case 'real'
ds=real(squeeze(dataset(d{1}, d{2}, d{3}, d{4}, d{5}, d{6}, d{7}, d{8})));
case 'imag'
ds=imag(squeeze(dataset(d{1}, d{2}, d{3}, d{4}, d{5}, d{6}, d{7}, d{8})));
end
if ~(axes_show(1) > axes_show(2)) %|| (axes_show(1)==0 && axes_show(2)==2 && ~(axes_show(1)==2))
ds=permute(ds, [2 1]);
end
end
%% Drawing function
function Draw_Line(draw)
if axes_show(2)~=0
im_handle=findobj('Tag',[get(axes_handle,'Tag') '_im']);
im_handle=im_handle(1);
im=get(im_handle,'CData');
% print value
if pt(1) > size(im,2)
pt(1)=ceil(size(ds,2)/2);
end
if pt(2) > size(im,1)
pt(2)=ceil(size(ds,1)/2);
end
set(line_text,'String',num2str(im(pt(2),pt(1))));
axes(liney_axes);
plot([1:size(im,2)],im(pt(2),:),'b');
title(liney_axes,['horizontal ' num2str(pt(2))]);
if ~(size(im,2)==1)
set(liney_axes,'XLim',[1,size(im,2)]);
end
if axes_handle==abs_axes,
set(liney_axes,'YLim',imagescale);
else
set(liney_axes,'YLim',[min(im(:)) max(im(:))]);
end;
axes(linex_axes);
plot([1:size(im,1)],im(:,pt(1)),'r');
title(linex_axes,['vertical ' num2str(pt(1))]);
if~(size(im,1)==1)
set(linex_axes,'XLim',[1,size(im,1)]);
end
if axes_handle==abs_axes,
set(linex_axes,'YLim',imagescale);
else
set(linex_axes,'YLim',[min(im(:)) max(im(:))]);
end;
%Draw line
axes(axes_handle);
if draw
line([pt(1) pt(1)],[1,size(ds,1)],'Color','r');
line([1,size(ds,2)],[pt(2) pt(2)],'Color','b');
end
end
end
%-----Draws Image
function Draw_Image(keep_threshold)
% ignore warning "Log of zero"
warning off MATLAB:log:logOfZero
create_slice;
if axes_show(2)~=0
% generate imagescale from thresholds
if isempty(imscale)
if ~keep_threshold
imagescale=double([min(ds(:)) max(ds(:))]);
threshold_min=min(ds(:));
threshold_max=max(ds(:));
set(threshold_min_text, 'String', num2str(threshold_min, '% 10.2f'));
set(threshold_max_text, 'String', num2str(threshold_max, '% 10.2f'));
else
imagescale=double([threshold_min, threshold_max]);
end
if ~isempty(imscale) && imagescale(1)==imagescale(2)
imagescale(2)=imagescale(2)+1;
end
else
imagescale=imscale;
end
% show image:
axes(abs_axes);
colormap(cmap);
abs_im=imagesc(ds,imagescale);
if strcmp(mysize, 'image')
axis image;
elseif strcmp(mysize, 'normal')
axis normal;
end
title(['(', num2str(n1), ',', num2str(n2), ',' num2str(n3), ',', num2str(n4), ',', num2str(n5), ',' num2str(n6), ',', num2str(n7), ',', num2str(n8), ')']);
set(abs_axes,'Tag','abs');
set(abs_im,'Tag','abs_im');
colorbar;
else
plot(squeeze(ds));
end
warning on MATLAB:log:logOfZero
end
end % end brViewer
|
github
|
philippboehmsturm/antx-master
|
readBrukerParamFile.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/functions/readBrukerParamFile.m
| 12,998 |
utf_8
|
82e420a2ecbc30090ca427cb80bfe7a4
|
function [paramStruct,headers]=readBrukerParamFile(filename)
% Reads Bruker JCAMP parameter files.
% especially: acqp and method files.
%
% Usage: [paramStruct,headers]=readBrukerParamFile(filename)
%
% paramStruct : Structure containing parameter variables.
% The parameter names are derived from the JCAMP tags.
% headers : Struct of strings containing 8 lines from file header
% filename : Name of the parameter file (including path).
%
%
% Requirements: the function reads the first 5 lines as header information
% and the 2 following lines of comments as additional header information.
% A file should be start in a kind like that:
% ##TITLE=Parameter List
% ##JCAMPDX=4.24
% ##DATATYPE=Parameter Values
% ##ORIGIN=Bruker BioSpin MRI GmbH
% ##OWNER=nmrsu
% $$ Tue May 8 17:08:14 2012 CEST (UT+2h) nmrsu
% $$ /opt/PV5.1/data/nmrsu/nmr/Matlab.dS1/1/acqp
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2013
% Bruker BioSpin MRI GmbH
% D-76275 Ettlingen, Germany
%
% All Rights Reserved
%
% $Id: readBrukerParamFile.m,v 1.3.4.2 2015/01/12 10:54:55 haas Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Opening and first tests
% Open parameter file
try
fid = fopen(filename,'r');
catch
fid = -1;
end
if fid == -1
error('Cannot open parameter file. Problem opening file %s.',filename);
end
% Init:
count = 0;
line=fgetl(fid);
headers=cell(15,2);
% generate HeaderInformation:
while ~(strncmp(line, '##$', 3))
count = count+1;
% Retreive the Labeled Data Record
[field,rem]=strtok(line,'=');
if ~(strncmp(line, '##', 2)) % it's a comment
headers{count,2} = strtrim(strtok(line,'$$'));
if strncmp(headers{count,2}, filesep, 1)
headers{count,1}='Path';
elseif strncmp(headers{count,2}, 'process', 7)
headers{count,1}='Process';
headers{count,2} = headers{count,2}(9:end);
else
pos=strfind(headers{count,2}(1:10), '-');
if strncmp(headers{count,2},'Mon',3)||strncmp(headers{count,2},'Tue',3)||strncmp(headers{count,2},'Wed',3)||strncmp(headers{count,2},'Thu',3)|| ...
strncmp(headers{count,2},'Fri',3)||strncmp(headers{count,2},'Sat',3)|| strncmp(headers{count,2},'Sun',3)|| ...
( strncmp(headers{count,2}, '20', 2) && length(pos)==2 )
headers{count,1}='Date';
end
end
else % it's a variable with ##
% Remove whitespaces and comments from the value
value = strtok(rem,'=');
headers{count,1}=strtrim(strtok(field,'##'));
headers{count,2} = strtrim(strtok(value,'$')); % save value without $
end
line=fgetl(fid);
end
headers=headers(1:count,:);
% Check if using a supported version of JCAMP file format
clear pos;
pos=find(strcmpi(headers(:,1), 'JCAMPDX')==1);
if isempty(pos)
pos=find(strcmpi(headers(:,1), 'JCAMP-DX')==1);
end
if ~isempty(pos) && length(pos)==1
version = sscanf(headers{pos,2},'%f');
if (version ~= 5)&&(version ~= 4.24)
warning(['JCAMP version %f is not supported. '...
'The function may not behave as expected.'],version);
end
else
error('Your fileheader is not correct')
end
%% Reading in parameters
% Initialization of parameter struct
paramStruct=struct;
% set start bool, because line is already read
first_round=true;
% Loop for reading parameters
while ~feof(fid)
% Reading in line
if ~first_round
line = getnext(fid);
end
first_round=false;
% Case of "$$ File finished" comment
if isempty(line)
continue;
end
try
[cell_field]=textscan(line,'##%s %s','delimiter','=');
field=cell_field{1};
value=cell_field{2};
catch
continue;
end
% Checking if field present and removing proprietary tag
try
field = field{1};
if strncmp(field,'$',1)
field=field(2:end);
end
catch
continue;
end
% Checking if value present otherwise value is set to empty string
try
value = value{1};
catch
value = '';
end
% Checking for END tag
if strcmp(field,'END')
continue;
end
% Checking if value is a struct, an array or a single value
if strncmp(value,'( ',2)
if(strncmp(value, '( <',3)||strncmp(value,'(<',2))
%is it an dynamic enum ?
if(strncmp(value, '( <',3))
value=getDynEnumValues(fid,[2],value);
elseif (strncmp(value,'(<',2))
value=getDynEnumValues(fid,[2],value);
end
else
sizes=textscan(value,'%f','delimiter','(,)');
sizes=sizes{:};
sizes=sizes(2:end).';
value=getArrayValues(fid,sizes,'');
try
if ~ischar(value{1}) || length(value)==1% possible datashredding with e.g. {'string1', 'string2'}
value=cell2mat(value);
end
end
end
elseif strncmp(value,'(',1)
value=getArrayValues(fid,1,value);
else
testNum = str2double(value);
if ~isnan(testNum)
value=testNum;
end
end
% Generating struct member
paramStruct.(field)=value;
end
%% getnext - gets the next valid line from the file,
% ignores comments and custom fields.
% -----------------------------------------------------------------
function data = getnext(fid)
% data : line data as a string
% fid : file identifier
% Read line
data = fgetl(fid);
% Throwing away comments and empty lines
while strncmp(data,'$$',2)||isempty(data)
if ~isempty(strfind(data,'File finished'))
data = '';
return;
end
data = fgetl(fid);
end
data=commentcheck(data);
% Checking for unexpected end of file
if data<0
error('Unexpected end of file: Missing END Statement')
end
%% getArrayValues - reads an array of values from the file.
% -----------------------------------------------------------------
function values=getArrayValues(fid,sizes,totalData)
% values : array values read from file
% fid : file identifier
% sizes : expected sizes of the array
% totalData : array data already read in
% Read until next JCAMP tag, comment or empty line; error if unexpected end
% of file occurs
pos = ftell(fid);
data = fgetl(fid);
while ~(strncmp(data,'##',2)||strncmp(data,'$$',2)||isempty(data))
%special-case: \ at end of line -> should be \n
if(strcmp(data(end),'\'))
totalData=[totalData data 'n '];
else
data=commentcheck(data);
totalData=[totalData data ];
end
pos = ftell(fid);
data = fgetl(fid);
end
fseek(fid, pos, 'bof');
if data<0
error('Unexpected end of file: Missing END Statement')
end
% Removing whitespaces at the edge of strings
totalData=strrep(totalData,'< ','<');
totalData=strrep(totalData,' >','>');
% Unpack compressed values. For example, replace @4*(0) with 0 0 0 0
expression = '@(\d+?)\*\((.+?)\)';
replace = '${repmat([$2 '' ''],1,str2num($1))}';
totalData = regexprep(totalData,expression,replace);
% Checking if array is a single string ...
if strncmp(totalData,'<',1)
%Stringarray?
totalData=strrep(totalData,'> <','><');
tempVal=textscan(totalData, '%s','delimiter','<>');
try
tempVal=tempVal{:};
catch
end
%Problem: the 'delimiter'-command also makes empty fields -> now we
%have to the not-empty fields:
count1=1;
values{1}='';
for i=2:2:length(tempVal) % 2:2: to keep empty string fields
%if(~isempty(tempVal{i}))
values{count1}=tempVal{i};
count1=count1+1;
%end
end
if length(values)==1 % dataloss possible by length >1 eg. {'string1', 'string2'}
try
values=values{:};
end
end
% ... or an array of structs ...
elseif strncmp(totalData,'(',1)
count1 = 1;
%get one struct:
while ~isempty(totalData)
[tempVal,totalData]=strtok(totalData,'()');
while ~(isempty(totalData) ...
|| ((length(totalData)>1) && (totalData(1)==')') && (totalData(2)==' ')) ...
|| ((length(totalData)==1) && (totalData(1)==')')));
[tempValAdd,totalData]=strtok(totalData,'()');
tempVal=[tempVal tempValAdd];
end
% split one struct in its parts:
if ~isempty(strtok(tempVal))
tempVal=textscan(tempVal,'%s','delimiter',',');
tempVal=tempVal{:};
for count2=1:length(tempVal);
if strncmp(tempVal{count2},'<',1)
[values{count2,count1}, rest]=strtok(tempVal{count2},'<>');
if length(rest)>3 % multiple seperate strings: <str> <dfg>
count3=1;
tmp=values{count2,count1};
values{count2, count1}={}; % change type to cell
values{count2, count1}{count3}=tmp; clear tmp;
while length(rest)>3
count3=count3+1;
[values{count2, count1}{count3}, rest]=strtok(rest(2:end),'< >');
end
end
else
testNum = str2double(tempVal{count2});
if ~isnan(testNum)
values{count2,count1}=testNum;
else
values{count2,count1}=tempVal{count2};
end
end
end
count1=count1+1;
end
end
count2=numel(values)/prod(sizes);
values=reshape(values,[count2 sizes]);
% ... or a simple array (most frequently numeric)
else
values=textscan(totalData,'%s');
totalStatus=true;
for count=1:length(values);
testNum = str2double(values{count});
if ~isnan(testNum)
values{count}=testNum;
else
totalStatus = false;
end
end
if totalStatus
values=cell2mat(values);
end
try
values=values{:};
end
%flip sizes, since the 'fastest' dimension in memory is the first on in
%matlab, but the last one in paravision
values=reshape(values,[fliplr(sizes) 1]);
%flip dimensions back to keep convention of paravision
values=permute(values,[ndims(values):-1:1]);
end
%% getArrayValues - reads an array of values from the file.
% -----------------------------------------------------------------
function values=getDynEnumValues(fid,sizes,totalData)
% values : array values read from file
% fid : file identifier
% sizes : expected sizes of the array
% totalData : array data already read in
% Read until next JCAMP tag, comment or empty line; error if unexpected end
% of file occurs
pos = ftell(fid);
data = fgetl(fid);
while ~(strncmp(data,'##',2)||strncmp(data,'$$',2)||isempty(data))
totalData=[totalData data ' '];
pos = ftell(fid);
data = fgetl(fid);
end
fseek(fid, pos, 'bof');
if data<0
error('Unexpected end of file: Missing END Statement')
end
%string shoud be '( <bla> , <blub> )'
not_empty=true;
count=1;
while (not_empty)
%Remove '( '
[trash, right]=strtok(totalData,'<');
right=right(2:end);%remove <
[left,right]=strtok(right,'>');
values{count, 1}=left;
[trash,right]=strtok(right,'<');
right=right(2:end);%remove <
[left,right]=strtok(right,'>');
values{count, 2}=left;
[trash,totalData]=strtok(right,'<');
not_empty=~isempty(totalData);
clear trash;
end
function data=commentcheck(data)
%string contains $$?
pos=strfind(data, '$$');
if ~isempty(pos)
%string contains also < or >?
if( ( ~isempty(strfind(data,'<')) ) || ( ~isempty(strfind(data,'>')) ) )
pos_strstart=strfind(data, '<');
pos_strend=strfind(data, '>');
%if $$ is between < > its ok, but if its not, w3e have to remove
%the rest of line
stop_check=false; % set true when comment found
for i=1:length(pos)
if(~stop_check)
comment_ok=false;
for j=1:min([length(pos_strstart), length(pos_strend)])
if (pos(i)>pos_strstart(j) && pos(i)<pos_strend(j))
comment_ok=true; % set comment_ok to false, when $$ is between of of the <> pairs
end
end
if ~comment_ok
disp(['"', data(pos(i):end), '" removed as comment']);
data=data(1:pos(i)-1);
end
end
end
else %string contains only $$ and no <>
disp([data(pos(1):end), ' removed as comment']);
data=data(1:pos(1)-1);
end
end
|
github
|
philippboehmsturm/antx-master
|
bruker_findDataname.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/functions/additional/bruker_findDataname.m
| 2,707 |
utf_8
|
a093e0564ed55d435e95e7e9a3d4d189
|
function out_findlist=bruker_findDataname(yourpath, dataname, you_disp)
% out_findlist=bruker_findDataname(yourpath, dataname, you_disp)
% searches in yourpath and all subdirectories for a file with the given dataname.
% IN:
% yourpath: string, name of the directory e.g. '/opt/PV6.0/data'
% dataname: string, name of the searched file, e.g. 'acqp'
% you_disp: if you add 'disp' as third argument: the list with found
% paths will getting displayed at the end of the search
%
% OUT:
% out_findlist: cellarray with paths to found files
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2012
% Bruker BioSpin MRI GmbH
% D-76275 Ettlingen, Germany
%
% All Rights Reserved
%
% $Id: bruker_findDataname.m,v 1.1.4.1 2014/05/23 08:43:51 haas Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
out_findlist={};
out_dirlist={};
start=dir(yourpath);
for i=1:length(start);
if start(i).isdir==1 && ~strcmp(start(i).name, '.') && ~strcmp(start(i).name, '..')
out_dirlist{length(out_dirlist)+1}=[yourpath, filesep, start(i).name];
end
if strcmp(start(i).name, dataname)
out_findlist{length(out_findlist)+1}=[yourpath, filesep, start(i).name];
end
end
if ~isempty(out_dirlist)
[out_dirlist, out_findlist]=recursive_find2dseq(out_dirlist, out_findlist, dataname);
end
% show:
if nargin==3 && strcmp(you_disp, 'disp')
for i=1:length(out_findlist)
disp(out_findlist{i});
end
end
end
% dirlist=cellarray mit verzeichnissen
function [out_dirlist, out_findlist]=recursive_find2dseq(in_dirlist, in_findlist, dataname)
out_dirlist=cell(1000,1);
out_findlist=in_findlist;
out_dirlist_counter=0;
for i1=1:length(in_dirlist)
s=dir(in_dirlist{i1});
for i2=3:length(s)
if s(i2).isdir %&& (~strcmp(s(i2).name, '.')) && (~strcmp(s(i2).name, '..'))
out_dirlist_counter=out_dirlist_counter+1;
out_dirlist{out_dirlist_counter}=[in_dirlist{i1}, filesep, s(i2).name];
if out_dirlist_counter==length(out_dirlist)
out_dirlist=[out_dirlist; cell(1000,1)];
end
end
if strcmp(s(i2).name, dataname)
out_findlist{length(out_findlist)+1}=[in_dirlist{i1}, filesep, s(i2).name];
end
end
end
out_dirlist=out_dirlist(1:out_dirlist_counter);
%disp(out_dirlist_counter)
if ~isempty(out_dirlist)
[out_dirlist, out_findlist]=recursive_find2dseq(out_dirlist, out_findlist, dataname);
end
end
|
github
|
philippboehmsturm/antx-master
|
bruker_writeVisu.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/functions/additional/exportToPV/bruker_writeVisu.m
| 13,299 |
utf_8
|
76f4fea33f8348c8fa2f8b70489cddb2
|
function bruker_writeVisu( writepath, exportVisu)
% bruker_writeVisu( writepath, exportVisu)
% writes a visu_pars-file.
% Please keep in mind, that it's not possible to write a function, that
% supports every possible change in the data and also supports all
% ParaVision-functions.
% This function only provides the most necessary parameters to get an image
% to ParaVision.
%
% Out: only writes files onto harddisk
% IN:
% writepath: type: string, path to the directory you want saving the Files
% it's recommended to set the path in following syntax:
% '/yourstudyname/expno/pdata/procno' where expno and procno are
% numbers
% exportVisu: contains the visu-parameters of the exportVisu-struct you want to import to the new
% visu_pars-file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2013
% Bruker BioSpin MRI GmbH
% D-76275 Ettlingen, Germany
%
% All Rights Reserved
%
% $Id: bruker_writeVisu.m,v 1.2.4.1 2014/05/23 08:43:51 haas Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Functioncall: write new visu-file
write_new_visu(writepath, exportVisu);
% perhaps in future releases it will be useful to add the generated Paramters to an existing File, therefore you can add more functions here.
end
%% Function: write new visu-file
function write_new_visu(writepath, exportVisu)
try
FileID=fopen([writepath, filesep, 'visu_pars'],'wb');
catch
FileID = -1;
end
if FileID == -1
error('Cannot create 2dseq file. Problem opening file %s.',[writepath, filesep, 'visu_pars']);
end
VisuCoreDim=exportVisu.VisuCoreDim;
VisuCoreFrameCount=exportVisu.VisuCoreFrameCount;
%% Header
fprintf(FileID, '%s\n', '##TITLE=Parameter List, pvmatlab');
fprintf(FileID, '%s\n', '##JCAMPDX=4.24');
fprintf(FileID, '%s\n', '##DATATYPE=Parameter Values');
fprintf(FileID, '%s\n', '##ORIGIN=Bruker BioSpin MRI GmbH');
fprintf(FileID, '%s\n', ['##OWNER=', exportVisu.OWNER]);
fprintf(FileID, '%s\n', ['$$ ', datestr(now, 'yyyy-mm-dd HH:MM:SS'), ' Matlab']);
fprintf(FileID, '%s\n', ['$$', writepath, filesep, 'visu_pars']);
fprintf(FileID, '%s\n', '$$ process Matlab');
% VisuUID
if isfield(exportVisu, 'VisuUid') && ~isempty(exportVisu.VisuUid)
fprintf(FileID, '%s\n', '##$VisuUid=( 64 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuUid, '>']);
end
% VisuVersion
fprintf(FileID, '%s\n', '##$VisuVersion=3');
% VisuCreator
fprintf(FileID, '%s\n', '##$VisuCreator=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuCreator, '>']);
% VisuCreatorVersion
fprintf(FileID, '%s\n', '##$VisuCreatorVersion=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuCreatorVersion, '>']);
% VisuCreationDate
fprintf(FileID, '%s\n', ['##$VisuCreationDate=<', exportVisu.VisuCreationDate, '>']);
% VisuInstanceModality
fprintf(FileID, '%s\n', '##$VisuInstanceModality=( 65 )');
fprintf(FileID, '%s\n', '<MR>');
% VisuCoreFrameCount
fprintf(FileID, '%s\n', ['##$VisuCoreFrameCount=', num2str(VisuCoreFrameCount)]);
% VisuCoreDim
fprintf(FileID, '%s\n', ['##$VisuCoreDim=', num2str(VisuCoreDim)]);
% VisuCoreSize
fprintf(FileID, '%s\n', ['##$VisuCoreSize=( ', num2str(VisuCoreDim), ' )']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreSize));
% VisuCoreDimDesc
if isfield(exportVisu, 'VisuCoreDimDesc') && ~isempty(exportVisu.VisuCoreDimDesc)
fprintf(FileID, '%s\n', ['##$VisuCoreDimDesc=( ', num2str(VisuCoreDim), ' )']);
tmp='';
for i=1:size(exportVisu.VisuCoreDimDesc,2)
if iscell(exportVisu.VisuCoreDimDesc)
tmp=[tmp, exportVisu.VisuCoreDimDesc{:,i}, ' '];
elseif ischar(exportVisu.VisuCoreDimDesc)
tmp=[tmp, exportVisu.VisuCoreDimDesc, ' '];
end
end
fprintf(FileID, '%s\n', tmp(1:end-1));
clear tmp;
end
% VisuCoreExtent
if isfield(exportVisu, 'VisuCoreExtent') && ~isempty(exportVisu.VisuCoreExtent)
fprintf(FileID, '%s\n', ['##$VisuCoreExtent=( ', num2str(VisuCoreDim), ' )']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreExtent));
end
% VisuCoreFrameThickness
if isfield(exportVisu, 'VisuCoreFrameThickness') && ~isempty(exportVisu.VisuCoreFrameThickness)
fprintf(FileID, '%s\n', ['##$VisuCoreFrameThickness=( ', num2str(length(exportVisu.VisuCoreFrameThickness)), ' )']);
if size(exportVisu.VisuCoreFrameThickness,2)==1
exportVisu.VisuCoreFrameThickness=exportVisu.VisuCoreFrameThickness';
end
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreFrameThickness));
end
% VisuCoreUnits
if isfield(exportVisu, 'VisuCoreUnits') && ~isempty(exportVisu.VisuCoreUnits)
fprintf(FileID, '%s\n', ['##$VisuCoreUnits=( ', num2str(VisuCoreDim), ', 65 )']);
if ischar(exportVisu.VisuCoreUnits) % very rare but e.g. [ppm]
tmp=['<', exportVisu.VisuCoreUnits, '> '];
else
tmp='';
for i=1:size(exportVisu.VisuCoreUnits,2)
if size(exportVisu.VisuCoreUnits,1)==1 && ~iscell(exportVisu.VisuCoreUnits)
tmp=[tmp, exportVisu.VisuCoreUnits(i), ' '];
else
tmp=[tmp, '<', exportVisu.VisuCoreUnits{i}, '> '];
end
end
end
fprintf(FileID, '%s\n', tmp(1:end-1));
clear tmp;
end
% VisuCoreOrientation
if isfield(exportVisu, 'VisuCoreOrientation') && ~isempty(exportVisu.VisuCoreOrientation)
VisuCoreOrientation=reshape(exportVisu.VisuCoreOrientation.', 1, numel(exportVisu.VisuCoreOrientation));
tmp='';
for i=1:length(VisuCoreOrientation)
tmp=[tmp, num2str(VisuCoreOrientation(i)), ' '];
end
fprintf(FileID, '%s\n', ['##$VisuCoreOrientation=( ', num2str(size(exportVisu.VisuCoreOrientation,1)), ', ', num2str(size(exportVisu.VisuCoreOrientation,2)), ' )']);
fprintf(FileID, '%s\n', tmp(1:end-1));
clear tmp;
end
% VisuCorePosition
if isfield(exportVisu, 'VisuCorePosition') && ~isempty(exportVisu.VisuCorePosition)
VisuCorePosition=reshape(exportVisu.VisuCorePosition.', 1, numel(exportVisu.VisuCorePosition));
tmp='';
for i=1:length(VisuCorePosition)
tmp=[tmp, num2str(VisuCorePosition(i)), ' '];
end
fprintf(FileID, '%s\n', ['##$VisuCorePosition=( ', num2str(size(exportVisu.VisuCorePosition,1)), ', ', num2str(size(exportVisu.VisuCorePosition,2)), ' )']);
fprintf(FileID, '%s\n', tmp(1:end-1));
clear tmp;
end
% VisuCoreInstanceType
if isfield(exportVisu, 'VisuInstanceType')
fprintf(FileID, '%s\n', ['##$VisuInstanceType=', exportVisu.VisuInstanceType ]);
end
% VisuCoreDataSlope
if isfield(exportVisu, 'VisuCoreDataSlope') && ~isempty(exportVisu.VisuCoreDataSlope)
fprintf(FileID, '%s\n', ['##$VisuCoreDataSlope=( ', num2str(VisuCoreFrameCount), ' ) ']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreDataSlope',15));
end
% VisuCoreDataOffs
if isfield(exportVisu, 'VisuCoreDataOffs') && ~isempty(exportVisu.VisuCoreDataOffs)
fprintf(FileID, '%s\n', ['##$VisuCoreDataOffs=( ', num2str(VisuCoreFrameCount), ' ) ']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreDataOffs',15));
end
% VisuCoreDataMin
if isfield(exportVisu, 'VisuCoreDataMin') && ~isempty(exportVisu.VisuCoreDataMin)
fprintf(FileID, '%s\n', ['##$VisuCoreDataMin=( ', num2str(VisuCoreFrameCount), ' ) ']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreDataMin',15));
end
% VisuCoreDataMax
if isfield(exportVisu, 'VisuCoreDataMax') && ~isempty(exportVisu.VisuCoreDataMax)
fprintf(FileID, '%s\n', ['##$VisuCoreDataMax=( ', num2str(VisuCoreFrameCount), ' ) ']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreDataMax',15));
end
% VisuCoreFrameType
if isfield(exportVisu, 'VisuCoreFrameType') && ~isempty(exportVisu.VisuCoreFrameType)
if iscell(exportVisu.VisuCoreFrameType)
tmp='';
for i=1:length(exportVisu.VisuCoreFrameType)
tmp=[tmp, exportVisu.VisuCoreFrameType{i}, ' '];
end
fprintf(FileID, '%s\n', ['##$VisuCoreFrameType=( ', num2str(length(exportVisu.VisuCoreFrameType)), ' )'] );
fprintf(FileID, '%s\n', tmp(1:end-1) );
clear tmp;
else
fprintf(FileID, '%s\n', ['##$VisuCoreFrameType=', exportVisu.VisuCoreFrameType] );
end
end
% VisuCoreWordType
if isfield(exportVisu, 'VisuCoreWordType') && ~isempty(exportVisu.VisuCoreWordType)
fprintf(FileID, '%s\n', ['##$VisuCoreWordType=', exportVisu.VisuCoreWordType]);
end
% VisuCoreByteOrder
if isfield(exportVisu, 'VisuCoreByteOrder') && ~isempty(exportVisu.VisuCoreByteOrder)
fprintf(FileID, '%s\n', ['##$VisuCoreByteOrder=', exportVisu.VisuCoreByteOrder]);
end
% VisuCoreTransposition
if isfield(exportVisu, 'VisuCoreTransposition') && ~isempty(exportVisu.VisuCoreTransposition)
fprintf(FileID, '%s\n', ['##$VisuCoreTransposition=( ', num2str(length(exportVisu.VisuCoreTransposition)), ' )']);
fprintf(FileID, '%s\n', num2str(exportVisu.VisuCoreTransposition' ) );
end
%VisuCoreDiskSliceOrder
if isfield(exportVisu, 'VisuCoreDiskSliceOrder') && ~isempty(exportVisu.VisuCoreDiskSliceOrder)
fprintf(FileID, '%s\n', ['##$VisuCoreDiskSliceOrder=', exportVisu.VisuCoreDiskSliceOrder]);
end
% VisuFGOrderDescDim
if isfield(exportVisu, 'VisuFGOrderDescDim') && ~isempty(exportVisu.VisuFGOrderDescDim)
fprintf(FileID, '%s\n', ['##$VisuFGOrderDescDim=', num2str(size(exportVisu.VisuFGOrderDesc,2))]);
end
% VisuFGOrderDesc
if isfield(exportVisu, 'VisuFGOrderDesc') && ~isempty(exportVisu.VisuFGOrderDesc)
fprintf(FileID, '%s\n', ['##$VisuFGOrderDesc=( ', num2str(size(exportVisu.VisuFGOrderDesc,2)), ' )']);
tmp='';
for i=1:size(exportVisu.VisuFGOrderDesc,2)
tmp=[tmp, sprintf('(%d, <%s>, <%s>, %d, %d) ', exportVisu.VisuFGOrderDesc{:,i})];
end
fprintf(FileID, '%s\n', tmp(1:end-1));
clear tmp;
end
% VisuGroupDepVals
if isfield(exportVisu, 'VisuGroupDepVals') && ~isempty(exportVisu.VisuGroupDepVals)
fprintf(FileID, '%s\n', ['##$VisuGroupDepVals=( ', num2str(size(exportVisu.VisuGroupDepVals,2)), ' )']);
tmp='';
for i=1:size(exportVisu.VisuGroupDepVals,2)
tmp=[tmp, sprintf('(<%s>, %d) ', exportVisu.VisuGroupDepVals{:,i})];
end
fprintf(FileID, '%s\n', tmp(1:end-1));
clear tmp;
end
% VisuSubjectName
if isfield(exportVisu, 'VisuSubjectName') && ~isempty(exportVisu.VisuSubjectName)
fprintf(FileID, '%s\n', '##$VisuSubjectName=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuSubjectName, '>']);
end
% VisuSubjectId
if isfield(exportVisu, 'VisuSubjectId') && ~isempty(exportVisu.VisuSubjectId)
fprintf(FileID, '%s\n', '##$VisuSubjectId=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuSubjectId, '>']);
end
% VisuStudyUid
if isfield(exportVisu, 'VisuStudyUid') && ~isempty(exportVisu.VisuStudyUid)
fprintf(FileID, '%s\n', '##$VisuStudyUid=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuStudyUid, '>']);
end
% VisuStudyId
if isfield(exportVisu, 'VisuStudyId') && ~isempty(exportVisu.VisuStudyId)
fprintf(FileID, '%s\n', '##$VisuStudyId=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuStudyId, '>']);
end
% VisuStudyNumber
if isfield(exportVisu, 'VisuStudyNumber') && ~isempty(exportVisu.VisuStudyNumber)
fprintf(FileID, '%s\n', ['##$VisuStudyNumber=', num2str(exportVisu.VisuStudyNumber)]);
end
% VisuExperimentNumber
if isfield(exportVisu, 'VisuExperimentNumber') && ~isempty(exportVisu.VisuExperimentNumber)
fprintf(FileID, '%s\n', ['##$VisuExperimentNumber=', num2str(exportVisu.VisuExperimentNumber)]);
end
% VisuProcesseingNumber
if isfield(exportVisu, 'VisuProcessingNumber') && ~isempty(exportVisu.VisuProcessingNumber)
fprintf(FileID, '%s\n', ['##$VisuProcessingNumber=', num2str(exportVisu.VisuProcessingNumber)]);
end
% VisuSubjectPosition
if isfield(exportVisu, 'VisuSubjectPosition') && ~isempty(exportVisu.VisuSubjectPosition)
fprintf(FileID, '%s\n', ['##$VisuSubjectPosition=', exportVisu.VisuSubjectPosition]);
end
% VisuSeriesTypeId
if isfield(exportVisu, 'VisuSeriesTypeId') && ~isempty(exportVisu.VisuSeriesTypeId)
fprintf(FileID, '%s\n', '##$VisuSeriesTypeId=( 65 )');
fprintf(FileID, '%s\n', ['<', exportVisu.VisuSeriesTypeId, '>']);
end
fprintf(FileID, '%s\n', '##END=');
fclose(FileID);
end
|
github
|
philippboehmsturm/antx-master
|
bruker_Reco.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/functions/additional/RECO/bruker_Reco.m
| 28,512 |
utf_8
|
43937a273b1ab73cc68c341a7694ff37
|
function [ data ] = bruker_Reco( recopart, data, Reco, varargin )
% [ data ] = bruker_Reco( recopart, data, Reco, ['RECO_Parametername', ParameterValues], ['RECO_Parametername2', ParameterValues2], ... )
% This function performs the steps of a reco based on the Bruker reco parameters.
% Normally you insert to this function the Reco parameter struct and overwrite some variables with additional arguments.
% This function also keeps the precision.
%
% E.g. [ data ] = bruker_Reco( 'all' , data, Reco, 'RECO_ft_size', [512; 512], 'RECO_size', [128; 128], 'RECO_offset', [192 192; 192 192]);
% The additonal arguments will overwrite the Reco parameters.
%
% IN:
% recopart: There are some recosteps, you can choose the steps with the recopart variable:
% recopart can be a string or a cell array with multiple strings.
% Your options:
% 'quadrature': uses RECO_qopts to set the correct phase to use the FT
% required parameters: RECO_qopts
% 'phase_rotate': in some cases it is necessary to shift the image. This option adds a phase offset to the frequency data to do this,
% therefore it uses the RECO_rotate variable. This method is recommended, because it also supportd subpixel shifts.
% required parameters: RECO_rotate
% 'zero_filling': Performs zero-filling.
% required parameters: RECO_ft_size and signal_position
% 'FT': The Fourier transformation
% required parameters: RECO_ft_mode
% 'image_rotate': in some cases it is necessarry to shift the image. This option shifts the image data to do this,
% therefore it uses the RECO_rotate variable.
% required parameters: RECO_rotate
% 'cutoff': reduces the size of the image. This is often used after zero filling and FT.
% required parameters: RECO_size, RECO_offset
% 'sumOfSquares': computes the sum of squares of the images from each receive channel.
% required parameters: none
% 'transposition': generates the transposition.
% required parameters: RECO_transposition
% 'all' : equivalent to recopart={'quadrature', 'phase_rotate', 'zero_filling', 'FT', 'cutoff', 'sumOfSquares', 'transposition'};
% required parameters: all listed above
%
% data: Your standard 7-dimensional cartesian k-space-Matrix
% varargin: You can add the Reco-parametername as string, followed by the value you want to set. Take a look at the example above.
%
% OUT:
% data: your datamatrix with 7-dimensions
%
%
% Parameters:
% ------------
%
% RECO_qopts - cellarray with string. This parameter determines the quadrature options that will be applied to the data in each dimension.
% The possible allowed values are:
% • NO_QOPTS - meaning is obvious.
% • COMPLEX_CONJUGATE - is the normal complex conjugate in which the imaginary component of each complex number is negated.
% - implies that every second complex point will be QUAD_NEGATION negated.
% • CONJ_AND_QNEG - combines both of the preceding two options. This will have the effect of alternately negating the real and imaginary
% component of the complex data points.
% The default quadrature options are:
% RECO_qopts{1} = 'QUAD_NEGATION' if AQ_mod = 'qseq',
% RECO_qopts{1} = 'CONJ_AND_QNEG' if AQ_mod = 'qsim',
% RECO_qopts{1}) = 'NO_QOPTS' otherwise.
% i > 1 -> RECO_qopts{i} = 'NO_QOPTS'.
%
% RECO_rotate - double array This parameter specifies a ‘roll’ of the data row which is carried out after the Fourier transformation
% and before the reduction implied by the RECO_size and RECO_offset parameters. This will shift all points
% in the data row towards the end of the row. Those points that ‘fall off’ the end will be reinserted at the start. This parameter must
% satisfy the relationship 0 ≤ RECO_rotate(i) < 1.
% If the user enters a value for this parameter which is greater than 1 and less than RECO_ft_size(i), the value for the parameter
% will be corrected by dividing the input by RECO_ft_size(i).
%
% RECO_ft_size - int array. This array contains the sizes of the complex data matrix in each direction after the FT but before it is output.
% The following two conditions must be satisfied:
% if i = 1 -> RECO_ft_size(i) ≥ ACQ_size(i)/2
% otherwise -> RECO_ft_size(i) ≥ ACQ_size(i) and RECO_ft_size(i) = 2^n .
% If FT processing is being done in the i-th dimension and if RECO_ft_size(i) ≠ ACQ_size(i)/2 if i = 0, RECO_ft_size(i) ≥ ACQ_size(i) otherwise,
% then zero-filling will be performed to expand the input dataset to the specified size.
%
% signal_position - column-vektor with NumberOfDimensions elements (maximum: 4) between 0 and 1. It defines the position of your data between the zeros.
% 0 means it's at the start of the line, and 1 means the data is at the end of the line. Default is a symmetric, means only values of 0.5
%
% RECO_size - int array. This array contains the sizes of the data matrix in each direction after output from the reconstruction.
% This parameter will specify the resolution of the image matrix in the reconstructed images.
% The following conditions must be satisfied:
% RECO_ft_size(i) ≥ RECO_size(i) > 0.
% Reducing the output size will also significantly reduce the required reconstruction time. Reducing the output size in the first
% direction will reduce the memory requirements for the reconstruction.
%
% RECO_offset - int array. When RECO_ft_size(i) ≠ RECO_size(i) the parameter RECO_size(i) determines the length of the output data row.
% The parameter RECO_offset(i,j) gives the starting point of the output for all rows in the i-th direction for the j-th image.
% This must be a two dimensional array since the desired offsets can change from one image to the next. The frequency offsets in a
% standard multi-slice experiment are a typical example. The following conditions must be satisfied:
% RECO_ft_size(i) > RECO_offset(i,j) ≥ 0 and
% RECO_ft_size(i) ≥ RECO_offset(i,j) + RECO_size(i)
%
% RECO_ft_mode - defined string. This parameter determines the type of FT to be performed in each direction.
% The allowed values for this parameter are:
% • NO_FT - meaning is obvious.
% • COMPLEX_FT - means that the input data is treated as complex. The results
% will be complex.
% • COMPLEX_IFT - means that the input data is treated as complex and an inverse Fourier transformation is performed.
% The default value for the FT mode is: RECO_ft_mode{i} = 'COMPLEX_FT', if i > 0 or AQ_mod = 'qsim'.
%
% RECO_transposition - array. This parameter can be used to transpose the final image matrix for each object during the reconstruction.
% The following conditions must be satisfied:
% 0 ≤ RECO_transposition(i) ≤ ACQ_dim, 0 ≤ i ≤ NI.
% A value of 0 (zero) implies that no transposition is desired. A value of 1 implies transposition of the first and
% second (read and phase) directions. A value of 2 implies transposition of the second and third (phase and slice) directions.
% A value of ACQ_dim implies transposition of the first and last directions.
% This parameter is ignored for all setup pipelines (e.g. GSP, GS Auto etc.). It will be forced to the value 0 (zero) if ACQ_dim = 1.
% Please note that the value of this parameter does not affect the interpretation of other reconstruction parameters.
% For example, the entries in the output parameter RECO_fov are not reordered to reflect the transposition.
% Also, the values of all other RECO parameters (RECO_ft_size, RECO_size, etc.) refer to the non-transposed data ordering.
% When the image processing parameters (the D3 class) are written to disk at the end of the reconstruction they are filled in
% so as to describe the transposed image matrix.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (c) 2013
% Bruker BioSpin MRI GmbH
% D-76275 Ettlingen, Germany
%
% All Rights Reserved
%
% $Id: bruker_Reco.m,v 1.4 2013/07/05 12:56:02 haas Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Calculate some necessary variables:
dims=[size(data,1), size(data,2), size(data,3), size(data,4)];
for i=1:4
if dims(i)>1
dimnumber=i;
end
end
NINR=size(data,6)*size(data,7);
%% parse Input-Variables
% needed in reco_qopts
[varargin, RECO_qopts] =bruker_addParamValue(varargin, 'RECO_qopts', '@(x) 1', []);
if ~isempty(RECO_qopts), Reco.RECO_qopts=RECO_qopts; end
% reco_x_rotate
[varargin, RECO_rotate] =bruker_addParamValue(varargin, 'RECO_rotate', '@(x) isnumeric(x)', []);
if ~isempty(RECO_rotate), Reco.RECO_rotate=RECO_rotate; end
% nedded in reco_zero_filling
[varargin, RECO_ft_size] =bruker_addParamValue(varargin, 'RECO_ft_size', '@(x) isnumeric(x)', []);
[varargin, RECO_offset] =bruker_addParamValue(varargin, 'RECO_offset', '@(x) isnumeric(x)', []);
[varargin, RECO_size] =bruker_addParamValue(varargin, 'RECO_size', '@(x) isnumeric(x)', []);
[varargin, signal_position] =bruker_addParamValue(varargin, 'signal_position', '@(x) isnumeric(x)', []);
if isempty(signal_position), signal_position=ones(dimnumber,1)*0.5; end
if ~isempty(RECO_ft_size), Reco.RECO_ft_size=RECO_ft_size; end
if ~isempty(RECO_offset), Reco.RECO_offset=RECO_offset; end
if ~isempty(RECO_size), Reco.RECO_size=RECO_size; end
% reco_ft
[varargin, RECO_ft_mode] =bruker_addParamValue(varargin, 'RECO_ft_mode', '@(x) ischar(x)', []);
if ~isempty(RECO_ft_mode), Reco.RECO_ft_mode=RECO_ft_mode; end
% RECO_transposition
[varargin, RECO_transposition] =bruker_addParamValue(varargin, 'RECO_transposition', '@(x) isnumeric(x)', []);
if ~isempty(RECO_transposition), Reco.RECO_transposition=RECO_transposition; end
if ~isempty(varargin)
error([varargin{1}, ' is not accepted.']);
end
%% covert some varibles
% all-option
if sum(strcmp(recopart, 'all')) >=1
recopart={'quadrature', 'phase_rotate', 'zero_filling', 'FT', 'cutoff', 'sumOfSquares', 'transposition'};
end
% precision
precision=whos('data');
precision=precision.class;
% all transposition the same?
same_transposition=true;
for i=1:length(Reco.RECO_transposition)
if ~isequal(Reco.RECO_transposition(i), Reco.RECO_transposition(1))
same_transposition=false;
end
end
% generate mapping-table: to map dim6 and dim7 to one frame/object-dimension
map=reshape(1:size(data,6)*size(data,7), [size(data,7), size(data,6)])';
% change recopart to cell
if ~iscell(recopart)
recopart={recopart};
end
%% start processing
for part=1:length(recopart)
switch recopart{part}
%% qudarature
case 'quadrature'
% errorcheck:
if isfield(Reco, 'RECO_qopts') && ischar(Reco.RECO_qopts)
if ~( strcmp(Reco.RECO_qopts, 'COMPLEX_CONJUGATE') || strcmp(Reco.RECO_qopts, 'QUAD_NEGATION') || strcmp(Reco.RECO_qopts, 'CONJ_AND_QNEG') || strcmp(Reco.RECO_qopts, 'NO_QOPTS') )
error('RECO_qopts has not the correct format');
end
elseif isfield(Reco, 'RECO_qopts') && iscell(Reco.RECO_qopts)
for i=1:length(Reco.RECO_qopts)
if ~( strcmp(Reco.RECO_qopts{i}, 'COMPLEX_CONJUGATE') || strcmp(Reco.RECO_qopts{i}, 'QUAD_NEGATION') || strcmp(Reco.RECO_qopts{i}, 'CONJ_AND_QNEG') || strcmp(Reco.RECO_qopts{i}, 'NO_QOPTS') )
error('RECO_qopts has not the correct format');
end
end
elseif isfield(Reco, 'RECO_qopts')
error('RECO_qopts has not the correct format');
end
if isfield(Reco, 'RECO_qopts') && iscell(Reco.RECO_qopts) && ~(length(Reco.RECO_qopts)==dimnumber)
error('RECO_qopts has not the correct format');
elseif isfield(Reco, 'RECO_qopts') && ~(iscell(Reco.RECO_qopts)) && ~(dimnumber==1)
error('RECO_qopts has not the correct format');
end
% start processing:
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
[ data(:,:,:,:,channel,NI,NR) ] = reco_qopts( data(:,:,:,:,channel,NI,NR) , Reco, map(NI, NR) );
end
end
end
%% phase_rotate
case 'phase_rotate'
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
[ data(:,:,:,:,channel,NI,NR) ] = reco_phase_rotate( data(:,:,:,:,channel,NI,NR) , Reco, NI );
end
end
end
%% zero-filling
case 'zero_filling'
% errorcheck
if isfield(Reco, 'RECO_ft_size') && ~( size(Reco.RECO_ft_size,2)==dimnumber && size(Reco.RECO_ft_size,1)==1 && length(size(Reco.RECO_ft_size))<=2 )
error('RECO_ft_size has not the correct format');
end
if isfield(Reco, 'signal_position') && ~( size(signal_position,2)==dimnumber && size(signal_position,1)==1 && length(size(signal_position))<=2 )
error('signal_position has not the correct format');
end
% init: zero-Matrix in correct precision
newdata_dims=[1 1 1 1];
newdata_dims(1:length(Reco.RECO_ft_size))=Reco.RECO_ft_size;
newdata=zeros([newdata_dims, size(data,5), size(data,6), size(data,7)], precision);
% function-calls:
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
newdata(:,:,:,:,channel,NI,NR) = reco_zero_filling( data(:,:,:,:,channel,NI,NR) , Reco, map(NI, NR), signal_position );
end
end
end
data=newdata;
clear newdata;
%% FT
case 'FT'
% errorcheck:
if isfield(Reco, 'RECO_ft_mode') && iscell(Reco.RECO_ft_mode)
for i=1:length(Reco.RECO_ft_mode)
if ~( strcmp(Reco.RECO_ft_mode{i}, 'COMPLEX_FT') || strcmp(Reco.RECO_ft_mode{i}, 'COMPLEX_FFT') || strcmp(Reco.RECO_ft_mode{i}, 'COMPLEX_IFT') || ...
strcmp(Reco.RECO_ft_mode{i}, 'COMPLEX_IFFT') || strcmp(Reco.RECO_ft_mode{i}, 'NO_FT') || strcmp(Reco.RECO_ft_mode{i}, 'NO_FFT') )
error('RECO_ft_mode has not the correct format');
end
end
elseif isfield(Reco, 'RECO_ft_mode') && ischar(Reco.RECO_ft_mode)
if ~( strcmp(Reco.RECO_ft_mode, 'COMPLEX_FT') || strcmp(Reco.RECO_ft_mode, 'COMPLEX_FFT') || strcmp(Reco.RECO_ft_mode, 'COMPLEX_IFT') || ...
strcmp(Reco.RECO_ft_mode, 'COMPLEX_IFFT') || strcmp(Reco.RECO_ft_mode, 'NO_FT') || strcmp(Reco.RECO_ft_mode, 'NO_FFT') )
error('RECO_ft_mode has not the correct format');
end
else
error('RECO_ft_mode has not the correct format');
end
% start processing:
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
[ data(:,:,:,:,channel,NI,NR) ] = reco_FT( data(:,:,:,:,channel,NI,NR) , Reco, map(NI, NR) );
end
end
end
%% image_rotate
case 'image_rotate'
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
[ data(:,:,:,:,channel,NI,NR) ] = reco_image_rotate( data(:,:,:,:,channel,NI,NR) , Reco, map(NI, NR) );
end
end
end
%% cutoff
case 'cutoff'
% errorcheck
if isfield(Reco, 'RECO_offset') && ~( size(Reco.RECO_offset,1)==dimnumber && size(Reco.RECO_offset,2)==size(data,6) && length(size(Reco.RECO_offset))<=2 )
error('RECO_offset has not the correct format');
end
if isfield(Reco, 'RECO_size') && ~( size(Reco.RECO_size,2)==dimnumber && size(Reco.RECO_size,1)==1 && length(size(Reco.RECO_size))<=2 )
error('RECO_size has not the correct format');
end
% init: zero-Matrix in correct precision
newdata_dims=[1 1 1 1];
newdata_dims(1:length(Reco.RECO_size))=Reco.RECO_size;
newdata=zeros([newdata_dims, size(data,5), size(data,6), size(data,7)], precision);
% function-calls:
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
newdata(:,:,:,:,channel,NI,NR) = reco_cutoff( data(:,:,:,:,channel,NI,NR) , Reco, NI );
end
end
end
data=newdata;
clear newdata;
%% sumOfSquares
case 'sumOfSquares'
for NR=1:size(data,7)
for NI=1:size(data,6)
data(:,:,:,:,1,NI,NR)=reco_channel_sumOfSquares( data(:,:,:,:,:,NI,NR) );
end
end
data=data(:,:,:,:,1, :, :);
%% transposition
case 'transposition'
% errorcheck:
if isfield(Reco, 'RECO_transposition') && ~( size(Reco.RECO_transposition,2)==size(data,6) && size(Reco.RECO_transposition,1)==1 && length(size(Reco.RECO_transposition))<=2 )
error('RECO_transposition has not the correct format');
end
% start processing:
% = special case -> speed up: do it not framwise
if same_transposition
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_transposition') )
error('RECO_transposition is missing')
end
% import variables:
RECO_transposition=Reco.RECO_transposition(1);
% calculate additional variables:
% start process
if RECO_transposition > 0
ch_dim1=mod(RECO_transposition, length(size(data(:,:,:,:,1,1,1))) )+1;
ch_dim2=RECO_transposition-1+1;
new_order=1:4;
new_order(ch_dim1)=ch_dim2;
new_order(ch_dim2)=ch_dim1;
data=permute(data, [new_order, 5, 6, 7]);
end
clear RECO_transposition;
else % = normal
for NR=1:size(data,7)
for NI=1:size(data,6)
for channel=1:size(data,5)
[ data(:,:,:,:,channel,NI,NR) ] = reco_transposition( data(:,:,:,:,channel,NI,NR) , Reco, NI );
end
end
end
end
end
end
end
%% reco_qopts
function frame=reco_qopts(frame, Reco, actual_framenumber)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_qopts') )
error('RECO_qopts is missing')
end
% import variables
RECO_qopts=Reco.RECO_qopts;
% claculate additional parameters
dims=[size(frame,1), size(frame,2), size(frame,3), size(frame,4)];
% check if the qneg-Matrix is necessary:
use_qneg=false;
if ( sum(strcmp(RECO_qopts, 'QUAD_NEGATION')) + sum(strcmp(RECO_qopts, 'CONJ_AND_QNEG')) )>=1
use_qneg=true;
qneg=ones(size(frame)); % Matrix containing QUAD_NEGATION multiplication matrix
end
% start preocess
for i=1:length(RECO_qopts)
switch(RECO_qopts{i})
case 'COMPLEX_CONJUGATE'
frame=conj(frame);
case 'QUAD_NEGATION'
switch i
case 1
qneg=qneg.*repmat([1, -1]', [ceil(dims(1)/2), dims(2), dims(3), dims(4)]);
case 2
qneg=qneg.*repmat([1, -1], [dims(1), ceil(dims(2)/2), dims(3), dims(4)]);
case 3
tmp(1,1,:)=[1,-1];
qneg=qneg.*repmat(tmp, [dims(1), dims(2), ceil(dims(3)/2), dims(4)]);
case 4
tmp(1,1,1,:)=[1,-1];
qneg=qneg.*repmat(tmp, [dims(1), dims(2), dims(3), ceil(dims(4)/2)]);
end
case 'CONJ_AND_QNEG'
frame=conj(frame);
switch i
case 1
qneg=qneg.*repmat([1, -1]', [ceil(dims(1)/2), dims(2), dims(3), dims(4)]);
case 2
qneg=qneg.*repmat([1, -1], [dims(1), ceil(dims(2)/2), dims(3), dims(4)]);
case 3
tmp(1,1,:)=[1,-1];
qneg=qneg.*repmat(tmp, [dims(1), dims(2), ceil(dims(3)/2), dims(4)]);
case 4
tmp(1,1,1,:)=[1,-1];
qneg=qneg.*repmat(tmp, [dims(1), dims(2), dims(3), ceil(dims(4)/2)]);
end
end
end
if use_qneg
% odd dimension size (ceil() does affekt the size)
if ~( size(qneg)==size(frame))
qneg=qneg(1:dims(1), 1:dims(2), 1:dims(3), 1:dims(4));
end
frame=frame.*qneg;
end
end
%% reco_phase_rotate
function frame=reco_phase_rotate(frame, Reco, actual_framenumber)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_rotate') )
error('RECO_rotate is missing')
end
% import variables:
RECO_rotate=Reco.RECO_rotate(:, actual_framenumber);
% calculate additional variables
dims=[size(frame,1), size(frame,2), size(frame,3), size(frame,4)];
% start process
phase_matrix=ones(size(frame));
for index=1:length(size(frame))
% written complete it would be:
% 0:1/dims(index):(1-1/dims(index));
% phase_vektor=exp(1i*2*pi*RECO_rotate(index)*dims(index)*f);
f=1:dims(index);
phase_vektor=exp(1i*2*pi*RECO_rotate(index)*f);
switch index
case 1
phase_matrix=phase_matrix.*repmat(phase_vektor', [1, dims(2), dims(3), dims(4)]);
case 2
phase_matrix=phase_matrix.*repmat(phase_vektor, [dims(1), 1, dims(3), dims(4)]);
case 3
tmp(1,1,:)=phase_vektor;
phase_matrix=phase_matrix.*repmat(tmp, [dims(1), dims(2), 1, dims(4)]);
case 4
tmp(1,1,1,:)=phase_vektor;
phase_matrix=phase_matrix.*repmat(tmp, [dims(1), dims(2), dims(3), 1]);
end
clear phase_vekor f tmp
end
frame=frame.*phase_matrix;
end
%% reco_zero_filling
function newframe=reco_zero_filling(frame, Reco, actual_framenumber, signal_position)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_ft_size') )
error('RECO_ft_size is missing')
end
% use function only if: Reco.RECO_ft_size is not equal to size(frame)
if ~( isequal(size(frame), Reco.RECO_ft_size ) )
if sum(signal_position >1)>=1 || sum(signal_position < 0)>=1
error('signal_position has to be a vektor between 0 and 1');
end
% import variables:
RECO_ft_size=Reco.RECO_ft_size;
% check if ft_size is correct:
for i=1:length(RECO_ft_size)
% if ~( log2(RECO_ft_size(i))-floor(log2(RECO_ft_size(i))) == 0 )
% error('RECO_ft_size has to be only of 2^n ');
% end
if RECO_ft_size(i) < size(frame,i)
error('RECO_ft_size has to be bigger than the size of your data-matrix')
end
end
% calculate additional variables
dims=[size(frame,1), size(frame,2), size(frame,3), size(frame,4)];
% start process
%Dimensions of frame and RECO_ft_size doesn't match? -> zerofilling
if ~( sum( size(frame)==RECO_ft_size )==length(RECO_ft_size) )
newframe=zeros(RECO_ft_size);
startpos=zeros(length(RECO_ft_size),1);
pos_ges={1, 1, 1, 1};
for i=1:length(RECO_ft_size)
diff=RECO_ft_size(i)-size(frame,i)+1;
startpos(i)=fix(diff*signal_position(i)+1);
if startpos(i)>RECO_ft_size(i)
startpos(i)=RECO_ft_size(i);
end
pos_ges{i}=startpos(i):startpos(i)+dims(i)-1;
end
newframe(pos_ges{1}, pos_ges{2}, pos_ges{3}, pos_ges{4})=frame;
else
newframe=frame;
end
clear startpos pos_ges diff;
else
newframe=frame;
end
end
%% reco_FT
function frame=reco_FT(frame, Reco, actual_framenumber)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_ft_mode') )
error('RECO_ft_mode is missing')
end
% import variables:
for i=1:4
if size(frame,i)>1
dimnumber=i;
end
end
if iscell(Reco.RECO_ft_mode)
for i=1:length(Reco.RECO_ft_mode)
if ~strcmp(strrep(Reco.RECO_ft_mode{i},'FFT','FT'), strrep(Reco.RECO_ft_mode{1},'FFT','FT'))
error(['It''s not allowed to use different transfomations on different Dimensions: ' Reco.RECO_ft_mode{:}]);
end
end
RECO_ft_mode=Reco.RECO_ft_mode{1};
else
RECO_ft_mode=Reco.RECO_ft_mode;
end
% start process
switch RECO_ft_mode
case {'COMPLEX_FT', 'COMPLEX_FFT'}
frame=fftn(frame);
case {'NO_FT', 'NO_FFT'}
% do nothing
case {'COMPLEX_IFT', 'COMPLEX_IFFT'}
frame=ifftn(frame);
otherwise
error('Your RECO_ft_mode is not supported');
end
end
%% reco_cutoff
function newframe=reco_cutoff(frame, Reco, actual_framenumber)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_size') )
error('RECO_size is missing')
end
% use function only if: Reco.RECO_ft_size is not equal to size(frame)
if ~( isequal(size(frame), Reco.RECO_size ) )
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_offset') )
error('RECO_offset is missing')
end
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_size') )
error('RECO_size is missing')
end
% import variables:
RECO_offset=Reco.RECO_offset(:, actual_framenumber);
RECO_size=Reco.RECO_size;
% cut the new part with RECO_size and RECO_offset
pos_ges={1, 1, 1, 1};
for i=1:length(RECO_size)
% +1 because RECO_offset starts with 0
pos_ges{i}=RECO_offset(i)+1:RECO_offset(i)+RECO_size(i);
end
newframe=frame(pos_ges{1}, pos_ges{2}, pos_ges{3}, pos_ges{4});
else
newframe=frame;
end
end
%% reco_image_rotate
function frame=reco_image_rotate(frame, Reco, actual_framenumber)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_rotate') )
error('RECO_rotate is missing')
end
% import variables:
RECO_rotate=Reco.RECO_rotate(:,actual_framenumber);
% start process
for i=1:length(size(frame))
pixelshift=zeros(4,1);
pixelshift(i)=round(RECO_rotate(i)*size(frame,i));
frame=circshift(frame, pixelshift);
end
end
%% channel_sumOfSquares
function newframe=reco_channel_sumOfSquares(frame, Reco, actual_framenumber)
dims=[size(frame,1), size(frame,2), size(frame,3), size(frame,4)];
newframe=zeros(dims);
for i=1:size(frame,5)
newframe=newframe+(abs(frame(:,:,:,:,i))).^2;
end
newframe=sqrt(newframe);
end
%% reco_transposition
function frame=reco_transposition(frame, Reco, actual_framenumber)
% check input
if ~(exist('Reco','var') && isstruct(Reco) && isfield(Reco, 'RECO_transposition') )
error('RECO_transposition is missing')
end
% import variables:
RECO_transposition=Reco.RECO_transposition(actual_framenumber);
% calculate additional variables:
dims=[size(frame,1), size(frame,2), size(frame,3), size(frame,4)];
% start process
if RECO_transposition > 0
ch_dim1=mod(RECO_transposition, length(size(frame)) )+1;
ch_dim2=RECO_transposition-1+1;
new_order=1:4;
new_order(ch_dim1)=ch_dim2;
new_order(ch_dim2)=ch_dim1;
frame=permute(frame, new_order);
frame=reshape(frame, dims);
end
end
|
github
|
philippboehmsturm/antx-master
|
paul.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/custom_functions/paul.m
| 1,061 |
utf_8
|
4943a1e7d8249af72f4b674c47d6e095
|
function [bmatrix bval bvec]=getBmatrix(methodfile)
% [bmatrix bval bvec]=getBmatrix(fullfile(pwd,'method'))
% fi=fullfile(pwd,'method')
% methfi='method'
% a=textread('%s',methfi,'delimiter','\n')
a=textread(methodfile,'%s','delimiter','\n');
%% n# B0 images
s1 =find(~cellfun(@isempty,regexpi(a,'^##\$PVM_DwAoImages=')));
nB0 =str2num(a{s1}( cell2mat(regexpi(a(s1),'='))+1 :end));
%% Bvec
s1=find(~cellfun(@isempty,regexpi(a,'^##\$PVM_DwDir=')))+1;
s2=find(~cellfun(@isempty,regexpi(a,'^##')) );
s2=s2(min(find(s2>s1)) )-1;
c= char(a(s1:s2));
c2='';
for i=1:size(c,1);
c2=[c2 ' ' c(i,:)];
end
c3=str2num(c2);
bvec=reshape(c3', [3 length(c3)/3])' ;
%% Bval
s1=find(~cellfun(@isempty,regexpi(a,'^##\$PVM_DwEffBval=')))+1;
s2=find(~cellfun(@isempty,regexpi(a,'^##')) );
s2=s2(min(find(s2>s1)) )-1;
c= char(a(s1:s2));
c2='';
for i=1:size(c,1)
c2=[c2 ' ' c(i,:)];
end
bval=str2num(c2)'
bval(1:nB0)=0; %set Bvalue for B0 to Zero
%% out
bmatrix=[ bval [ zeros(nB0,3);bvec ] ]
|
github
|
philippboehmsturm/antx-master
|
getBmatrix.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/custom_functions/getBmatrix.m
| 1,063 |
utf_8
|
ad6206dad77c1dc44d2348b07d98668d
|
function [bmatrix bval bvec]=getBmatrix(methodfile)
% [bmatrix bval bvec]=getBmatrix(fullfile(pwd,'method'))
% fi=fullfile(pwd,'method')
% methfi='method'
% a=textread('%s',methfi,'delimiter','\n')
a=textread(methodfile,'%s','delimiter','\n');
%% n# B0 images
s1 =find(~cellfun(@isempty,regexpi(a,'^##\$PVM_DwAoImages=')));
nB0 =str2num(a{s1}( cell2mat(regexpi(a(s1),'='))+1 :end));
%% Bvec
s1=find(~cellfun(@isempty,regexpi(a,'^##\$PVM_DwDir=')))+1;
s2=find(~cellfun(@isempty,regexpi(a,'^##')) );
s2=s2(min(find(s2>s1)) )-1;
c= char(a(s1:s2));
c2='';
for i=1:size(c,1);
c2=[c2 ' ' c(i,:)];
end
c3=str2num(c2);
bvec=reshape(c3', [3 length(c3)/3])' ;
%% Bval
s1=find(~cellfun(@isempty,regexpi(a,'^##\$PVM_DwEffBval=')))+1;
s2=find(~cellfun(@isempty,regexpi(a,'^##')) );
s2=s2(min(find(s2>s1)) )-1;
c= char(a(s1:s2));
c2='';
for i=1:size(c,1)
c2=[c2 ' ' c(i,:)];
end
bval=str2num(c2)' ;
bval(1:nB0)=0; %set Bvalue for B0 to Zero
%% out
bmatrix=[ bval [ zeros(nB0,3);bvec ] ];
|
github
|
philippboehmsturm/antx-master
|
read2dseq.m
|
.m
|
antx-master/mritools/pvtools_bruker/pvtools_bruker/custom_functions/read2dseq.m
| 1,926 |
utf_8
|
5769be3724b77cc6ebb5fe4ec6d4946a
|
function fid=read2dseq(path,RO,PE,frame,type);
%reads Bruker data
%path: path to 2dseq file, ends with filesep
%RO: Readout matrix size
%PE: Phase encoding matrix size
%frame: frame to open (equals the slice for 3D data)
%type: 'int16'/'int32' for 16/32 bit signed integer
%
%SUBFUNCTION
%slopefind retrieves the PV slope factor from the RECO file
%
%full path to file
filepath=fullfile(path,'2dseq');
%Open 2dseq
%FC=fopen([filepath,'2dseq'] ); % for SG
[FC, message]=fopen(filepath,'r+','l'); %for PC
%FC=fopen([filepath,'2dseq'], 'r','l'); %for CD
%Read file
%for 16 bit images
if strcmp(type,'int16')==1
fseek(FC,RO*PE*(frame-1)*2,'bof');
ftell(FC);
fid=fread(FC,[RO,PE],'int16');
end
%for 32 bit images
if strcmp(type,'int32')==1
fseek(FC,RO*PE*(frame-1)*4,'bof');
ftell(FC);
fid=fread(FC,[RO,PE],'int32');
end
fclose(FC);
fid=fid';
%extract slope factor and correct image for it
slope=slopefind(path);
fid=(1/slope)*fid;
end
%%%%%%%%%%%%%%%%%%%%%%%SUBFUNCTION%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function slope=slopefind(path);
%slopefind extracts the slope factor off the RECO file stored in the path
a=fopen([path,'reco']);
line1=1;
position=0;
line2=['##$RECO_map_slope=( 2 )'];
line22=line2(1:19);
while line1~=-1
fseek(a,position,'bof');
line1=fgets(a); %Read line from file, keep newline character
% line1=fgetl(a); %Read line from file, discard newline character
k=length(line1);
if k>=19
line11=line1(1:19);
else
line11=line1;
end
if strcmp(line22,line11)==1 %string compare
line1=-1;
position=ftell(a);
line3=fgets(a);
else
position=ftell(a);
end
end
fclose(a);
l=length(line3);
j=0;
i=1;
while i<=l
if isspace(line3(i))==1 %looks for space (end of paramater)
j=i-1;
i=l+1;
else
i=i+1;
end
end
line4=line3(1:j);
slope=str2num(line4);
end
|
github
|
philippboehmsturm/antx-master
|
gifoverlay2.m
|
.m
|
antx-master/mritools/various/gifoverlay2.m
| 640 |
utf_8
|
423cfc1505f0dbd5fafaaa03cacfff78
|
%% simple check overlay
function gifoverlay2(handles,outname,resol )
%
% outname=fullfile(pwd, 'test.gif')
% handles=[1 2]
% resol='-r300'
[paout fi]=fileparts(outname);
warning off;
figure(handles(1));
print(handles(1), '-djpeg',['-r' num2str(resol)],fullfile(paout, 'vv1.jpg'));
figure(handles(2));
print(handles(2), '-djpeg',['-r' num2str(resol)],fullfile(paout, 'vv2.jpg'));
ls2={
fullfile(paout, 'vv1.jpg');
fullfile(paout, 'vv2.jpg');
};
makegif([ strrep(outname,'.gif','') '.gif'] ,ls2,.2);
delete(fullfile(paout, 'vv1.jpg'));
delete(fullfile(paout, 'vv2.jpg'));
|
github
|
philippboehmsturm/antx-master
|
radd.m
|
.m
|
antx-master/mritools/various/radd.m
| 544 |
utf_8
|
508b788db36aea78aa2bfb1c78a078ba
|
function filename2=radd(filename, str2add, tail)
% filename2=radd(filename, str2add, tail)
% add string (prefix/suffix) to filename
%% IN
% filename ... filename
% str2add ... str to add
% tail ...[1/2]...prefix/suffix
%% OUT
% filename2
%% example
% filename2=radd('V:\mrm\msk_fNat.nii', 'W', 1)
% filename2=radd('V:\mrm\msk_fNat.nii', 'W', 2)
[pa2 fi2 ext2]=fileparts(filename);
if tail==1
filename2=fullfile(pa2, [str2add fi2 ext2]);
else
filename2=fullfile(pa2, [ fi2 str2add ext2]) ;
end
|
github
|
philippboehmsturm/antx-master
|
resize_img4.m
|
.m
|
antx-master/mritools/various/resize_img4.m
| 5,644 |
utf_8
|
4f2a20a75586c6f41e30f75760cec726
|
function outfile=resize_img4(imnames, Voxdim, BB, ismask, interpmethod,suffix, dt)
%% resample images to have specified voxel dims and BBox, NewName with suffix, optional: dt(numeric class)
% function outfile=resize_img4(imnames, Voxdim, BB, ismask, interpmethod,suffix, dt)
% resize_img2 -- resample images to have specified voxel dims and BBox
% resize_img2(imnames, voxdim, bb, ismask,interpmethod)
% outfile: filename written
% Output images will be prefixed with 'r', and will have voxel dimensions
%
% suffix: if suffix has format-end (.nii)-->file will be saves as such
% -->instead of suffix
% equal to voxdim. Use NaNs to determine voxdims from transformation matrix
% of input image(s).
% If bb == nan(2,3), bounding box will include entire original image
% Origin will move appropriately. Use world_bb to compute bounding box from
% a different image.
% interpmethod: 0/1.. : NN/linear... see SPM
%
% Pass ismask=true to re-round binary mask values (avoid
% growing/shrinking masks due to linear interp)
%
% See also voxdim, world_bb
% Based on John Ashburner's reorient.m
% http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7
% http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2
% Adapted by Ged Ridgway -- email bugs to [email protected]
% This version doesn't check spm_flip_analyze_images -- the handedness of
% the output image and matrix should match those of the input.
% Check spm version:
if exist('spm_select','file') % should be true for spm5
spm5 = 1;
elseif exist('spm_get','file') % should be true for spm2
spm5 = 0;
else
error('Can''t find spm_get or spm_select; please add SPM to path')
end
spm_defaults;
% prompt for missing arguments
if ( ~exist('imnames','var') || isempty(char(imnames)) )
if spm5
imnames = spm_select(inf, 'image', 'Choose images to resize');
else
imnames = spm_get(inf, 'img', 'Choose images to resize');
end
end
% check if inter fig already open, don't close later if so...
Fint = spm_figure('FindWin', 'Interactive'); Fnew = [];
if ( ~exist('Voxdim', 'var') || isempty(Voxdim) )
Fnew = spm_figure('GetWin', 'Interactive');
Voxdim = spm_input('Vox Dims (NaN for "as input")? ',...
'+1', 'e', '[nan nan nan]', 3);
end
if ( ~exist('BB', 'var') || isempty(BB) )
Fnew = spm_figure('GetWin', 'Interactive');
BB = spm_input('Bound Box (NaN => original)? ',...
'+1', 'e', '[nan nan nan; nan nan nan]', [2 3]);
end
if ~exist('ismask', 'var')
ismask = false;
end
if isempty(ismask)
ismask = false;
end
% reslice images one-by-one
vols = spm_vol(imnames);
for V=vols'
% (copy to allow defaulting of NaNs differently for each volume)
voxdim = Voxdim;
bb = BB;
% default voxdim to current volume's voxdim, (from mat parameters)
if any(isnan(voxdim))
vprm = spm_imatrix(V.mat);
vvoxdim = vprm(7:9);
voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim));
end
voxdim = voxdim(:)';
mn = bb(1,:);
mx = bb(2,:);
% default BB to current volume's
if any(isnan(bb(:)))
vbb = world_bb(V);
vmn = vbb(1,:);
vmx = vbb(2,:);
mn(isnan(mn)) = vmn(isnan(mn));
mx(isnan(mx)) = vmx(isnan(mx));
end
% voxel [1 1 1] of output should map to BB mn
% (the combination of matrices below first maps [1 1 1] to [0 0 0])
mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]);
% voxel-coords of BB mx gives number of voxels required
% (round up if more than a tenth of a voxel over)
imgdim = ceil(mat \ [mx 1]' - 0.1)';
%===============================================
VO = V;
[pth,nam,ext] = fileparts(V.fname);
if isempty(suffix);
suffix='r';
VO.fname = fullfile(pth,[ nam suffix ext]);
else
[pa2 fi2 ext2]=fileparts(suffix);
if isempty(ext2) %%PREFIX
% suffix='r';
VO.fname = fullfile(pth,[ nam suffix ext]);
else %% NEW NAME
VO.fname = suffix;
end
end
if exist('dt') && length(dt)==2
VO.dt =dt;
end
% output image
VO.dim(1:3) = imgdim(1:3);
VO.mat = mat;
VO = spm_create_vol(VO);
spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed');
for i = 1:imgdim(3)
M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat);
% img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp)
img = spm_slice_vol(V, M, imgdim(1:2), interpmethod); % (linear interp)
if ismask
img = round(img);
end
spm_write_plane(VO, img, i);
spm_progress_bar('Set', i)
end
spm_progress_bar('Clear');
end
% call spm_close_vol if spm2
if ~spm5
spm_close_vol(VO);
end
if (isempty(Fint) && ~isempty(Fnew))
% interactive figure was opened by this script, so close it again.
close(Fnew);
end
%disp('Done.')
outfile=VO.fname;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bb = world_bb(V)
% world-bb -- get bounding box in world (mm) coordinates
d = V.dim(1:3);
% corners in voxel-space
c = [ 1 1 1 1
1 1 d(3) 1
1 d(2) 1 1
1 d(2) d(3) 1
d(1) 1 1 1
d(1) 1 d(3) 1
d(1) d(2) 1 1
d(1) d(2) d(3) 1 ]';
% corners in world-space
tc = V.mat(1:3,1:4)*c;
% bounding box (world) min and max
mn = min(tc,[],2)';
mx = max(tc,[],2)';
bb = [mn; mx];
|
github
|
philippboehmsturm/antx-master
|
pdisp.m
|
.m
|
antx-master/mritools/various/pdisp.m
| 284 |
utf_8
|
3458ee4bfd47c59000c9413d63dde89b
|
% function pdisp(i)
% disp iterationnumber in one line
% example
% for i=1:10; pdisp(i);end
% pdisp(i,10);%show everey 10th
function pdisp(i,varargin)
if nargin==2
if mod(i,varargin{1})==0
fprintf(1,'%d ',i);
end
else
fprintf(1,'%d ',i);
end
|
github
|
philippboehmsturm/antx-master
|
affine.m
|
.m
|
antx-master/mritools/various/affine.m
| 16,664 |
utf_8
|
419b609560eb98534c0e32cc4506cc7f
|
% Using 2D or 3D affine matrix to rotate, translate, scale, reflect and
% shear a 2D image or 3D volume. 2D image is represented by a 2D matrix,
% 3D volume is represented by a 3D matrix, and data type can be real
% integer or floating-point.
%
% You may notice that MATLAB has a function called 'imtransform.m' for
% 2D spatial transformation. However, keep in mind that 'imtransform.m'
% assumes y for the 1st dimension, and x for the 2nd dimension. They are
% equivalent otherwise.
%
% In addition, if you adjust the 'new_elem_size' parameter, this 'affine.m'
% is equivalent to 'interp2.m' for 2D image, and equivalent to 'interp3.m'
% for 3D volume.
%
% Usage: [new_img new_M] = ...
% affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);
%
% old_img - original 2D image or 3D volume. We assume x for the 1st
% dimension, y for the 2nd dimension, and z for the 3rd
% dimension.
%
% old_M - a 3x3 2D affine matrix for 2D image, or a 4x4 3D affine
% matrix for 3D volume. We assume x for the 1st dimension,
% y for the 2nd dimension, and z for the 3rd dimension.
%
% new_elem_size (optional) - size of voxel along x y z direction for
% a transformed 3D volume, or size of pixel along x y for
% a transformed 2D image. We assume x for the 1st dimension
% y for the 2nd dimension, and z for the 3rd dimension.
% 'new_elem_size' is 1 if it is default or empty.
%
% You can increase its value to decrease the resampling rate,
% and make the 2D image or 3D volume more coarse. It works
% just like 'interp3'.
%
% verbose (optional) - 1, 0
% 1: show transforming progress in percentage
% 2: progress will not be displayed
% 'verbose' is 1 if it is default or empty.
%
% bg (optional) - background voxel intensity in any extra corner that
% is caused by the interpolation. 0 in most cases. If it is
% default or empty, 'bg' will be the average of two corner
% voxel intensities in original data.
%
% method (optional) - 1, 2, or 3
% 1: for Trilinear interpolation
% 2: for Nearest Neighbor interpolation
% 3: for Fischer's Bresenham interpolation
% 'method' is 1 if it is default or empty.
%
% new_img - transformed 2D image or 3D volume
%
% new_M - transformed affine matrix
%
% Example 1 (3D rotation):
% load mri.mat; old_img = double(squeeze(D));
% old_M = [0.88 0.5 3 -90; -0.5 0.88 3 -126; 0 0 2 -72; 0 0 0 1];
% new_img = affine(old_img, old_M, 2);
% [x y z] = meshgrid(1:128,1:128,1:27);
% sz = size(new_img);
% [x1 y1 z1] = meshgrid(1:sz(2),1:sz(1),1:sz(3));
% figure; slice(x, y, z, old_img, 64, 64, 13.5);
% shading flat; colormap(map); view(-66, 66);
% figure; slice(x1, y1, z1, new_img, sz(1)/2, sz(2)/2, sz(3)/2);
% shading flat; colormap(map); view(-66, 66);
%
% Example 2 (2D interpolation):
% load mri.mat; old_img=D(:,:,1,13)';
% old_M = [1 0 0; 0 1 0; 0 0 1];
% new_img = affine(old_img, old_M, [.2 .4]);
% figure; image(old_img); colormap(map);
% figure; image(new_img); colormap(map);
%
% This program is inspired by:
% SPM5 Software from Wellcome Trust Centre for Neuroimaging
% http://www.fil.ion.ucl.ac.uk/spm/software
% Fischer, J., A. del Rio (2004). A Fast Method for Applying Rigid
% Transformations to Volume Data, WSCG2004 Conference.
% http://wscg.zcu.cz/wscg2004/Papers_2004_Short/M19.pdf
%
% - Jimmy Shen ([email protected])
%
function [new_img, new_M] = affine(old_img, old_M, new_elem_size, verbose, bg, method)
if ~exist('old_img','var') | ~exist('old_M','var')
error('Usage: [new_img new_M] = affine(old_img, old_M, [new_elem_size], [verbose], [bg], [method]);');
end
if ndims(old_img) == 3
if ~isequal(size(old_M),[4 4])
error('old_M should be a 4x4 affine matrix for 3D volume.');
end
elseif ndims(old_img) == 2
if ~isequal(size(old_M),[3 3])
error('old_M should be a 3x3 affine matrix for 2D image.');
end
else
error('old_img should be either 2D image or 3D volume.');
end
if ~exist('new_elem_size','var') | isempty(new_elem_size)
new_elem_size = [1 1 1];
elseif length(new_elem_size) < 2
new_elem_size = new_elem_size(1)*ones(1,3);
elseif length(new_elem_size) < 3
new_elem_size = [new_elem_size(:); 1]';
end
if ~exist('method','var') | isempty(method)
method = 1;
elseif ~exist('bresenham_line3d.m','file') & method == 3
error([char(10) char(10) 'Please download 3D Bresenham''s line generation program from:' char(10) char(10) 'http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=21057' char(10) char(10) 'to test Fischer''s Bresenham interpolation method.' char(10) char(10)]);
end
% Make compatible to MATLAB earlier than version 7 (R14), which
% can only perform arithmetic on double data type
%
old_img = double(old_img);
old_dim = size(old_img);
if ~exist('bg','var') | isempty(bg)
bg = mean([old_img(1) old_img(end)]);
end
if ~exist('verbose','var') | isempty(verbose)
verbose = 1;
end
if ndims(old_img) == 2
old_dim(3) = 1;
old_M = old_M(:, [1 2 3 3]);
old_M = old_M([1 2 3 3], :);
old_M(3,:) = [0 0 1 0];
old_M(:,3) = [0 0 1 0]';
end
% Vertices of img in voxel
%
XYZvox = [ 1 1 1
1 1 old_dim(3)
1 old_dim(2) 1
1 old_dim(2) old_dim(3)
old_dim(1) 1 1
old_dim(1) 1 old_dim(3)
old_dim(1) old_dim(2) 1
old_dim(1) old_dim(2) old_dim(3) ]';
old_R = old_M(1:3,1:3);
old_T = old_M(1:3,4);
% Vertices of img in millimeter
%
XYZmm = old_R*(XYZvox-1) + repmat(old_T, [1, 8]);
% Make scale of new_M according to new_elem_size
%
new_M = diag([new_elem_size 1]);
% Make translation so minimum vertex is moved to [1,1,1]
%
new_M(1:3,4) = round( min(XYZmm,[],2) );
% New dimensions will be the maximum vertices in XYZ direction (dim_vox)
% i.e. compute dim_vox via dim_mm = R*(dim_vox-1)+T
% where, dim_mm = round(max(XYZmm,[],2));
%
new_dim = ceil(new_M(1:3,1:3) \ ( round(max(XYZmm,[],2))-new_M(1:3,4) )+1)';
% Initialize new_img with new_dim
%
new_img = zeros(new_dim(1:3));
% Mask out any changes from Z axis of transformed volume, since we
% will traverse it voxel by voxel below. We will only apply unit
% increment of mask_Z(3,4) to simulate the cursor movement
%
% i.e. we will use mask_Z * new_XYZvox to replace new_XYZvox
%
mask_Z = diag(ones(1,4));
mask_Z(3,3) = 0;
% It will be easier to do the interpolation if we invert the process
% by not traversing the original volume. Instead, we traverse the
% transformed volume, and backproject each voxel in the transformed
% volume back into the original volume. If the backprojected voxel
% in original volume is within its boundary, the intensity of that
% voxel can be used by the cursor location in the transformed volume.
%
% First, we traverse along Z axis of transformed volume voxel by voxel
%
for z = 1:new_dim(3)
if verbose & ~mod(z,10)
fprintf('%.2f percent is done.\n', 100*z/new_dim(3));
end
% We need to find out the mapping from voxel in the transformed
% volume (new_XYZvox) to voxel in the original volume (old_XYZvox)
%
% The following equation works, because they all equal to XYZmm:
% new_R*(new_XYZvox-1) + new_T == old_R*(old_XYZvox-1) + old_T
%
% We can use modified new_M1 & old_M1 to substitute new_M & old_M
% new_M1 * new_XYZvox == old_M1 * old_XYZvox
%
% where: M1 = M; M1(:,4) = M(:,4) - sum(M(:,1:3),2);
% and: M(:,4) == [T; 1] == sum(M1,2)
%
% Therefore: old_XYZvox = old_M1 \ new_M1 * new_XYZvox;
%
% Since we are traverse Z axis, and new_XYZvox is replaced
% by mask_Z * new_XYZvox, the above formula can be rewritten
% as: old_XYZvox = old_M1 \ new_M1 * mask_Z * new_XYZvox;
%
% i.e. we find the mapping from new_XYZvox to old_XYZvox:
% M = old_M1 \ new_M1 * mask_Z;
%
% First, compute modified old_M1 & new_M1
%
old_M1 = old_M; old_M1(:,4) = old_M(:,4) - sum(old_M(:,1:3),2);
new_M1 = new_M; new_M1(:,4) = new_M(:,4) - sum(new_M(:,1:3),2);
% Then, apply unit increment of mask_Z(3,4) to simulate the
% cursor movement
%
mask_Z(3,4) = z;
% Here is the mapping from new_XYZvox to old_XYZvox
%
M = old_M1 \ new_M1 * mask_Z;
switch method
case 1
new_img(:,:,z) = trilinear(old_img, new_dim, old_dim, M, bg);
case 2
new_img(:,:,z) = nearest_neighbor(old_img, new_dim, old_dim, M, bg);
case 3
new_img(:,:,z) = bresenham(old_img, new_dim, old_dim, M, bg);
end
end; % for z
if ndims(old_img) == 2
new_M(3,:) = [];
new_M(:,3) = [];
end
return; % affine
%--------------------------------------------------------------------
function img_slice = trilinear(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
TINY = 5e-2; % tolerance
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X, and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
% within boundary of original image
%
if ( old_X > 1-TINY & old_X < xdim2+TINY & ...
old_Y > 1-TINY & old_Y < ydim2+TINY & ...
old_Z > 1-TINY & old_Z < zdim2+TINY )
% Calculate distance of old_XYZ to its neighbors for
% weighted intensity average
%
dx = old_X - floor(old_X);
dy = old_Y - floor(old_Y);
dz = old_Z - floor(old_Z);
x000 = floor(old_X);
x100 = x000 + 1;
if floor(old_X) < 1
x000 = 1;
x100 = x000;
elseif floor(old_X) > xdim2-1
x000 = xdim2;
x100 = x000;
end
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
y000 = floor(old_Y);
y010 = y000 + 1;
if floor(old_Y) < 1
y000 = 1;
y100 = y000;
elseif floor(old_Y) > ydim2-1
y000 = ydim2;
y010 = y000;
end
y100 = y000;
y001 = y000;
y101 = y000;
y110 = y010;
y011 = y010;
y111 = y010;
z000 = floor(old_Z);
z001 = z000 + 1;
if floor(old_Z) < 1
z000 = 1;
z001 = z000;
elseif floor(old_Z) > zdim2-1
z000 = zdim2;
z001 = z000;
end
z100 = z000;
z010 = z000;
z110 = z000;
z101 = z001;
z011 = z001;
z111 = z001;
x010 = x000;
x001 = x000;
x011 = x000;
x110 = x100;
x101 = x100;
x111 = x100;
v000 = double(img(x000, y000, z000));
v010 = double(img(x010, y010, z010));
v001 = double(img(x001, y001, z001));
v011 = double(img(x011, y011, z011));
v100 = double(img(x100, y100, z100));
v110 = double(img(x110, y110, z110));
v101 = double(img(x101, y101, z101));
v111 = double(img(x111, y111, z111));
img_slice(x,y) = v000*(1-dx)*(1-dy)*(1-dz) + ...
v010*(1-dx)*dy*(1-dz) + ...
v001*(1-dx)*(1-dy)*dz + ...
v011*(1-dx)*dy*dz + ...
v100*dx*(1-dy)*(1-dz) + ...
v110*dx*dy*(1-dz) + ...
v101*dx*(1-dy)*dz + ...
v111*dx*dy*dz;
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % trilinear
%--------------------------------------------------------------------
function img_slice = nearest_neighbor(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
% initialize new_Y accumulation
%
Y2X = 0;
Y2Y = 0;
Y2Z = 0;
for y = 1:ydim1
% increment of new_Y accumulation
%
Y2X = Y2X + M(1,2); % new_Y to old_X
Y2Y = Y2Y + M(2,2); % new_Y to old_Y
Y2Z = Y2Z + M(3,2); % new_Y to old_Z
% backproject new_Y accumulation and translation to old_XYZ
%
old_X = Y2X + M(1,4);
old_Y = Y2Y + M(2,4);
old_Z = Y2Z + M(3,4);
for x = 1:xdim1
% accumulate the increment of new_X and apply it
% to the backprojected old_XYZ
%
old_X = M(1,1) + old_X ;
old_Y = M(2,1) + old_Y ;
old_Z = M(3,1) + old_Z ;
xi = round(old_X);
yi = round(old_Y);
zi = round(old_Z);
% within boundary of original image
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % nearest_neighbor
%--------------------------------------------------------------------
function img_slice = bresenham(img, dim1, dim2, M, bg)
img_slice = zeros(dim1(1:2));
% Dimension of transformed 3D volume
%
xdim1 = dim1(1);
ydim1 = dim1(2);
% Dimension of original 3D volume
%
xdim2 = dim2(1);
ydim2 = dim2(2);
zdim2 = dim2(3);
for y = 1:ydim1
start_old_XYZ = round(M*[0 y 0 1]');
end_old_XYZ = round(M*[xdim1 y 0 1]');
[X Y Z] = bresenham_line3d(start_old_XYZ, end_old_XYZ);
% line error correction
%
% del = end_old_XYZ - start_old_XYZ;
% del_dom = max(del);
% idx_dom = find(del==del_dom);
% idx_dom = idx_dom(1);
% idx_other = [1 2 3];
% idx_other(idx_dom) = [];
%del_x1 = del(idx_other(1));
% del_x2 = del(idx_other(2));
% line_slope = sqrt((del_x1/del_dom)^2 + (del_x2/del_dom)^2 + 1);
% line_error = line_slope - 1;
% line error correction removed because it is too slow
for x = 1:xdim1
% rescale ratio
%
i = round(x * length(X) / xdim1);
if i < 1
i = 1;
elseif i > length(X)
i = length(X);
end
xi = X(i);
yi = Y(i);
zi = Z(i);
% within boundary of the old XYZ space
%
if ( xi >= 1 & xi <= xdim2 & ...
yi >= 1 & yi <= ydim2 & ...
zi >= 1 & zi <= zdim2 )
img_slice(x,y) = img(xi,yi,zi);
% if line_error > 1
% x = x + 1;
% if x <= xdim1
% img_slice(x,y) = img(xi,yi,zi);
% line_error = line_slope - 1;
% end
% end % if line_error
% line error correction removed because it is too slow
else
img_slice(x,y) = bg;
end % if boundary
end % for x
end % for y
return; % bresenham
|
github
|
philippboehmsturm/antx-master
|
montage_p.m
|
.m
|
antx-master/mritools/various/montage_p.m
| 1,770 |
utf_8
|
eb9b9391e88e62127f637cbe1ebae34a
|
function montage_p(u,lis,xopengl,grids,varargin)
% montage_p(u,lis,xopengl,grids)
% example: montage_p(dat,[],1,1)
% u=3dmatrix :sliced allong 3rd. dim
% lis=[2val] :c-limits
% xopengl=[0,1] :normal/opengl
% grid [0/1]; grid off/on
cla;
u=single(u);
if ~exist('lis');lis=[];end
if ~exist('xopengl');xopengl=[1];end
if ~exist('grids');grids=[1];end
if isempty(lis)
lis=[min(u(:)) max(u(:))];
end
if isempty(xopengl)
xopengl=0;
end
si=size(u);
if length(si)>2
n=ceil(sqrt(si(3)));
else
n=1;
end
r=zeros(n*si(1),n*si(2) );
p=1;
sp=[];col=[];
for i=1:n %zeileblock
for j=1:n %spaltenblock
try
dx= u(:,:,p);
catch
dx=zeros(size( u(:,:,1) ))+ mean(u(:));
end
tx=i*si(1)-si(1)+1;
ty=j*si(2)-si(2)+1;
sp(end+1,1)=ty(1);
col(end+1,1)=tx(1);
r(tx:tx+si(1)-1 , ty:ty+si(2)-1 ) = dx ;
p=p+1;
end
end
if nargin==5
% % sizf=varargin{1}
% % H = fspecial('average',sizf);
% % r2 = imfilter(r,H,'replicate');
% % fg,imagesc(r2)
else
imagesc(r) ;
% imagescnan(r) ;
end
% imagescnan(r) ;hold on;
%contourf(r,30);hold on
% [f1 f2]=gradient(r,.1);quiver(f1,f2,'color','k','linewidth',2);
% set(gca,'ydir','reverse')
% grid on;
if grids==1
col=unique(col);
sp=unique(sp);
hold on;
try
for i=1:length(sp)
vline(sp(i),'color',[1 1 1]);
end
for i=1:length(col)
hline(col(i),'color',[1 1 1]);
end
end
end
if lis(1)~=lis(2) %if not the same limits
caxis(lis);
end
% if xopengl==1
% set(gcf,'Renderer','opengl');
% end
|
github
|
philippboehmsturm/antx-master
|
getvolume.m
|
.m
|
antx-master/mritools/various/getvolume.m
| 1,582 |
utf_8
|
885adc09d31962f32db7b9f07c5b0413
|
function [ vol nvox h2]=getvolume(fili,operation)
% calc volume (qmm) &nvox from file
% fili: niftifile
% operation: (optional) logical operation to searchn in volume, 3>,>=3,>3,...~=3
% (optional: the voxvalues of '1' are counted)
% output: volume(qmm) ,number of voxels, header
% example:
% [ vol nvox h2]=getvolume(fili)
% [ vol nvox h2]=getvolume(fili,'==1')
% [ vol nvox h2]=getvolume(fili,'>0')
if 0
fili=fullfile(pwd,'Xwmask2.nii')
operation='==1'
end
if exist('fili')==0; fili=[]; end
if exist('operation')==0; operation='==1'; end
if isempty(fili)
%manual select
[files,sts] = spm_select(inf,'image','select mouse folders',[],pwd,'.*');
if isempty(files); return; end
files=cellstr(files);
fili=files;
end
% if ~exist('operation')
% % if isempty(operation)
% operation='==1';
% end
if ischar(fili)
[h2 d2 xyz2]=rgetnii(fili);
eval([ 'idx=find(d2' operation ');']);
nvox=length(idx);
% vol=(abs(prod(diag(h2.mat(1:3,1:3)))) ) *(nvox); %brain volume(qmm)
vol=abs(det(h2.mat(1:3,1:3)) *(nvox)); %brain volume(qmm)
else
for i=1:length(fili)
disp(['calc vol: ' fili{i}]);
[h2 d2 xyz2]=rgetnii(fili{i});
eval([ 'idx=find(d2' operation ');']);
nvox(i,1)=length(idx);
% vol(i,1)=(abs(prod(diag(h2.mat(1:3,1:3)))) ) *(nvox(i)); %brain volume(qmm)
vol(i,1)= abs(det(h2.mat(1:3,1:3)) *(nvox(i)));
end
h2=[fili num2cell([vol nvox])];
end
|
github
|
philippboehmsturm/antx-master
|
rmricron.m
|
.m
|
antx-master/mritools/various/rmricron.m
| 3,560 |
utf_8
|
9c2a4b94aa147df46b8a711f591b32c6
|
function rmricron(pa,tmp,ovl,cols, trans)
%% use MRICRON to plot data
% function rmricron(pa,tmp,ovl,cols, trans)
% rmricron(pa,tmp,ovl,cols, trans)
% pa : path
% tmp : template (without path)
% ovl: overlaying images (struct, without path)
% cols: colors =numeric idx from pulldown LUT in mricron
% trans: 2 values: transparency background/overlay & transperancy between overlays
%% example
% pa='V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1'
% tmp='_AwAVGT.nii'
% ovl={...
% 'H_wc1T2_left.nii'
% 'H_wc1T2_right.nii'
% 'H_wc2T2_right.nii'
% 'H_wc2T2_left.nii'
% }
% cols=[ 2 2 1 1 ];
% trans=[20 -1]
% rmricron(pa,tmp,ovl,cols, trans)
if 0
pa='V:\projects\atlasRegEdemaCorr\niiSubstack\s20150908_FK_C1M01_1_3_1_1'
tmp='_AwAVGT.nii'
ovl={...
'H_wc1T2_left.nii'
'H_wc1T2_right.nii'
'H_wc2T2_right.nii'
'H_wc2T2_left.nii'
}
cols=[ 2 2 1 1 ];
trans=[20 -1]
rmricron(pa,tmp,ovl,cols, trans)
end
% start mricron .\templates\ch2.nii.gz -c -0 -l 20 -h 140 -o .\templates\ch2bet.nii.gz -c -1 10 -h 130
% color: "-c bone", "-c 0", gray, -c 1 is red...
% start /MAX c:\mricron\mricron
% clim: -l and -h for lower/upper value
% trasnparency of overlays: -b : -1, 0:20:100, -1=addititive
% trasnparency between overlays: -t : -1, 0:20:100, -1=addititive
% H_wmask2_left.nii
% H_wT2_left.nii H_whemi2_left.nii
% H_wT2_right.nii H_whemi2_right.nii
% pa='V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1'
% ovl={...
% 'H_wc1T2_left.nii'
% 'H_wc1T2_right.nii'
% 'H_wc2T2_right.nii'
% 'H_wc2T2_left.nii'
% }
% tmp='_AwAVGT.nii'
ov=fullpath(pa,ovl);
tmp=char(fullpath(pa,tmp));
% trans=[20 -1]
% col={ 'r' '1'
% 'b' '2'
% 'g' '3'
% 'v' '4'
% 'y' '5'
% 'c' '6'
% }
% cols=[ 2 2 1 1 ]% 2 2]
cols2=[];
for i=1:length(ov)
cols2{i,1}=[' -c -' num2str(cols(i)) ' '];
end
ov2=cellfun(@(a,b) [' -o ' a b] ,ov,cols2,'UniformOutput',0);
o = reshape(char(ov2)', 1, []);
btrans=[' -b ' num2str(trans(1)) ];
ttrans=[' -t ' num2str(trans(2)) ];
mri='!start c:\mricron\mricron ';
mri='!start /MAX c:\mricron\mricron ';
tmp=fullfile(pa, '_AwAVGT.nii');
c=[mri tmp o btrans ttrans];
eval(c);
% !start c:\mricron\mricron V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\_AwAVGT.nii -o V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\H_wc1T2_right.nii -c - 4 -o V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\H_wc2T2_right.nii -c - 1 -b -50 -t - 50
%
% !start c:\mricron\mricron V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\_AwAVGT.nii -o V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\H_wc1T2_right.nii -c -6 -b -50
% -o V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\H_wc2T2_right.nii -c 1 -b 50 -t 50
%
%
% !start c:\mricron\mricron V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\_AwAVGT.nii -o V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\H_wc1T2_right.nii -c 4 -o V:\projects\atlasRegEdemaCorr\nii\s20150908_FK_C1M04_1_3_1_1\H_wc2T2_right.nii -c 1 -b 50 -t 50
%
%
%
% % mri='!start /MAX c:\mricron\mricron'
% mri='!start c:\mricron\mricron '
% tmp=fullfile(pa, '_AwAVGT.nii')
% f1=fullfile(pa, 'H_wT2_left.nii')
% f1=ov{1}
% box=[' -o ' f1 ]
%
% c=[mri tmp box ]
% eval(c)
%
%
%
|
github
|
philippboehmsturm/antx-master
|
replacefilepath.m
|
.m
|
antx-master/mritools/various/replacefilepath.m
| 377 |
utf_8
|
dd36d8d1e3460c05ae138883cc51c8a8
|
%% replace path of file(string/cell) or files(cell) with 'path'
% example
% replacefilepath(parafiles2,pwd);
function in2=replacefilepath(in,path)
if ischar(in)
in=cellstr(in);
charis=1;
else
charis=0;
end
for i=1: size(in,1)
[pa fi ext]=fileparts(in{i,1});
in2{i,1}=fullfile(path,[fi ext]);
end
if charis==1
in2=char(in2);
end
|
github
|
philippboehmsturm/antx-master
|
fullpath.m
|
.m
|
antx-master/mritools/various/fullpath.m
| 358 |
utf_8
|
3df8f8ee52a574444b5c6e448077f7a7
|
function fp=fullpath( pa,a)
%add path(pa) to cellarray of files (a)
% function fp=fullpath( a, pa)
% a={'wc1T2.nii' 'wc2T2.nii' 'wc3T2.nii'}
% pa=pwd
% fp=fullpath( pa,a)
if isempty(a)
fp=[];
return
end
if iscell(a)
fp=cellfun(@(a) [ fullfile(pa,a)] ,a, 'UniformOutput',0);
fp=fp(:);
else
fp=fullfile(pa,a);
end
|
github
|
philippboehmsturm/antx-master
|
mni2idx.m
|
.m
|
antx-master/mritools/various/mni2idx.m
| 2,091 |
utf_8
|
0bc25cf0792bd5790e06393e41c3052d
|
function res=mni2idx(cords, hdr, mode )
% convert cords from [idx to mni] or [mni to idx]
% cords must be [3xX]
% ===========================
% convert idx2mni
% res=mni2idx( orig.x.XYZ(:,1:10000) , orig.x.hdr, 'idx2mni' );
% sum(sum(orig.x.XYZmm(:,1:10000)-res'))
% % convert mni2idx
% res=mni2idx( orig.x.XYZmm(:,1:10000) , orig.x.hdr, 'mni2idx' );
% test: sum(sum(orig.x.XYZ(:,1:10000)-res'))
% hdr =orig.x.hdr;
% xyz =orig.x.XYZ;
% xyzmm =orig.x.XYZmm;
hb=hdr.mat;
%% idx2mni
if strcmp(mode,'idx2mni')
q=cords;
%q=xyz(:,i);
Q =[q ; ones(1,size(q,2))];
Q2=Q'*hb';
Q2=Q2(:,1:3);
res=Q2;
% n=xyzmm(:,i)'
% Q2-n
elseif strcmp(mode,'mni2idx')
%% mni2idx
si=size(cords);
if si(1)==1
cords=cords';
end
Q2=cords';
%Q2= xyzmm(:,i)';
Q2=[Q2 ones(size(Q2,1),1)] ;
Q =hb\Q2';
Q=Q(1:3,:)';
% f=xyz(:,i)'
% Q-f
res=Q;
else
error('use idx2mni or mni2idx');
end
%
%
%
% orig.x.XYZ
% orig.x.XYZmm
% orig.x.hdr
%
%
% m=orig.x.hdr.mat
% hb=m
% s_x=hb(1,:);%hb.hdr.hist.srow_x;
% s_y=hb(2,:);%hb.hdr.hist.srow_y;
% s_z=hb(3,:);%hb.hdr.hist.srow_z;
%
% for j=1:10000
% i=j
% q=orig.x.XYZ(:,i);
% n=orig.x.XYZmm(:,i);
%
%
% % s_x(find(s_x(1:3)==0))=1;
% % s_y(find(s_y(1:3)==0))=1;
% % s_z(find(s_z(1:3)==0))=1;
%
%
% ff=q';
%
% nc(:,1) = s_x(1).* ff(:,1) + s_x(2).* ff(:,2) + s_x(3).* ff(:,3) + s_x(4);
% nc(:,2) = s_y(1).* ff(:,1) + s_y(2).* ff(:,2) + s_y(3).* ff(:,3) + s_y(4);
% nc(:,3) = s_z(1).* ff(:,1) + s_z(2).* ff(:,2) + s_z(3).* ff(:,3) + s_z(4);
%
% q(:)'
% n(:)'
% nc(:)'
%
% nn(j,:)=nc;
% end
%
% % sum(sum(abs(nn-Q2)))
%
% %% idx2mni
% i=1:5
%
% q=orig.x.XYZ(:,i)
% Q =[q ; ones(1,size(q,2))];
% Q2=Q'*hb';
% Q2=Q2(:,1:3)
% n=orig.x.XYZmm(:,i)'
%
% Q2-n
%
% %% mni2idx
% Q2= orig.x.XYZmm(:,i)';
% Q2=[Q2 ones(size(Q2,1),1)] ;
% Q =hb\Q2';
% Q=Q(1:3,:)'
%
% f=orig.x.XYZ(:,i)'
%
% Q-f
%
|
github
|
philippboehmsturm/antx-master
|
rreslice2target.m
|
.m
|
antx-master/mritools/various/rreslice2target.m
| 863 |
utf_8
|
83ecbe500cbe4308dc3e6eaa143496b9
|
function [h,d ]=rreslice2target(fi2merge, firef, fi2save, interpx,dt)
% [h,d ]=rreslice2target(fi2merge, firef, fi2save)
% if [fi2save] is empty/not existing..parse to workspace
if ~exist('interpx')
interpx=1;
end
[inhdr, inimg]=rgetnii(fi2merge);
[tarhdr ]=rgetnii(firef);
% inhdr=spm_vol(fi2merge);
% inimg=spm_read_vols(inhdr);
% [h, d] = nii_reslice_target(inhdr, inimg, tarhdr, 'false') ;
% if interpx==1
% [h, d] = nii_reslice_target(inhdr, inimg, tarhdr, 'true') ;
% else
% [h, d] = nii_reslice_target(inhdr, inimg, tarhdr, 'false') ;
% end
[h, d] = nii_reslice_target(inhdr, inimg, tarhdr, interpx) ;
if exist('fi2save')
if ~isempty(fi2save)
if exist('dt')~=1
rsavenii(fi2save,h,d );
else
rsavenii(fi2save,h,d,dt );
end
end
end
|
github
|
philippboehmsturm/antx-master
|
resize_img2.m
|
.m
|
antx-master/mritools/various/resize_img2.m
| 4,792 |
utf_8
|
02533111854336430b465df20b8ba8e3
|
function resize_img2(imnames, Voxdim, BB, ismask, interpmethod)
% resize_img2 -- resample images to have specified voxel dims and BBox
% resize_img2(imnames, voxdim, bb, ismask,interpmethod)
%
% Output images will be prefixed with 'r', and will have voxel dimensions
% equal to voxdim. Use NaNs to determine voxdims from transformation matrix
% of input image(s).
% If bb == nan(2,3), bounding box will include entire original image
% Origin will move appropriately. Use world_bb to compute bounding box from
% a different image.
% interpmethod: 0/1.. : NN/linear... see SPM
%
% Pass ismask=true to re-round binary mask values (avoid
% growing/shrinking masks due to linear interp)
%
% See also voxdim, world_bb
% Based on John Ashburner's reorient.m
% http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7
% http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2
% Adapted by Ged Ridgway -- email bugs to [email protected]
% This version doesn't check spm_flip_analyze_images -- the handedness of
% the output image and matrix should match those of the input.
% Check spm version:
if exist('spm_select','file') % should be true for spm5
spm5 = 1;
elseif exist('spm_get','file') % should be true for spm2
spm5 = 0;
else
error('Can''t find spm_get or spm_select; please add SPM to path')
end
spm_defaults;
% prompt for missing arguments
if ( ~exist('imnames','var') || isempty(char(imnames)) )
if spm5
imnames = spm_select(inf, 'image', 'Choose images to resize');
else
imnames = spm_get(inf, 'img', 'Choose images to resize');
end
end
% check if inter fig already open, don't close later if so...
Fint = spm_figure('FindWin', 'Interactive'); Fnew = [];
if ( ~exist('Voxdim', 'var') || isempty(Voxdim) )
Fnew = spm_figure('GetWin', 'Interactive');
Voxdim = spm_input('Vox Dims (NaN for "as input")? ',...
'+1', 'e', '[nan nan nan]', 3);
end
if ( ~exist('BB', 'var') || isempty(BB) )
Fnew = spm_figure('GetWin', 'Interactive');
BB = spm_input('Bound Box (NaN => original)? ',...
'+1', 'e', '[nan nan nan; nan nan nan]', [2 3]);
end
if ~exist('ismask', 'var')
ismask = false;
end
if isempty(ismask)
ismask = false;
end
% reslice images one-by-one
vols = spm_vol(imnames);
for V=vols'
% (copy to allow defaulting of NaNs differently for each volume)
voxdim = Voxdim;
bb = BB;
% default voxdim to current volume's voxdim, (from mat parameters)
if any(isnan(voxdim))
vprm = spm_imatrix(V.mat);
vvoxdim = vprm(7:9);
voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim));
end
voxdim = voxdim(:)';
mn = bb(1,:);
mx = bb(2,:);
% default BB to current volume's
if any(isnan(bb(:)))
vbb = world_bb(V);
vmn = vbb(1,:);
vmx = vbb(2,:);
mn(isnan(mn)) = vmn(isnan(mn));
mx(isnan(mx)) = vmx(isnan(mx));
end
% voxel [1 1 1] of output should map to BB mn
% (the combination of matrices below first maps [1 1 1] to [0 0 0])
mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]);
% voxel-coords of BB mx gives number of voxels required
% (round up if more than a tenth of a voxel over)
imgdim = ceil(mat \ [mx 1]' - 0.1)';
% output image
VO = V;
[pth,nam,ext] = fileparts(V.fname);
VO.fname = fullfile(pth,['r' nam ext]);
VO.dim(1:3) = imgdim(1:3);
VO.mat = mat;
VO = spm_create_vol(VO);
spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed');
for i = 1:imgdim(3)
M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat);
% img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp)
img = spm_slice_vol(V, M, imgdim(1:2), interpmethod); % (linear interp)
if ismask
img = round(img);
end
spm_write_plane(VO, img, i);
spm_progress_bar('Set', i)
end
spm_progress_bar('Clear');
end
% call spm_close_vol if spm2
if ~spm5
spm_close_vol(VO);
end
if (isempty(Fint) && ~isempty(Fnew))
% interactive figure was opened by this script, so close it again.
close(Fnew);
end
disp('Done.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bb = world_bb(V)
% world-bb -- get bounding box in world (mm) coordinates
d = V.dim(1:3);
% corners in voxel-space
c = [ 1 1 1 1
1 1 d(3) 1
1 d(2) 1 1
1 d(2) d(3) 1
d(1) 1 1 1
d(1) 1 d(3) 1
d(1) d(2) 1 1
d(1) d(2) d(3) 1 ]';
% corners in world-space
tc = V.mat(1:3,1:4)*c;
% bounding box (world) min and max
mn = min(tc,[],2)';
mx = max(tc,[],2)';
bb = [mn; mx];
|
github
|
philippboehmsturm/antx-master
|
rmkmask.m
|
.m
|
antx-master/mritools/various/rmkmask.m
| 1,601 |
utf_8
|
bf0cbb77c96e38867bf3a033217b487e
|
function [fileout h d ]=rmkmask(file,threshoperation, val1, val0, dowritefile )
%% make mask , suffixes '_msk' if written to disk
% [fileout h d ]=rmkmask(file,threshoperation, val1, val0, dowritefile )
%% In
% file: niftifile
% threshoperation: string (operation&value) , e.g '>0' ,'>=1.24'
% val1: value to replace trueValues (ones) , e.g 3, 1000...
% val0: value to replace falseValues (zeros) , e.g nan, inf..-1000
% dowritefile : [0,1]..no/jes
%% out:
% h, d ..header, data
%% example
% [fileout h d ]=rmkmask('T2brain.nii','>0',[],[],1); %write
% [fileout h d ]=rmkmask('T2brain.nii','>0',[],[],0); %doNotwrite
% [fileout h d ]=rmkmask('T2brain.nii','>0', 5, nan, 1 ); %set true=5,false=nan
% [fileout h d ]=rmkmask('T2brain.nii','==0', 5, nan, 1 ); reverse
% file ='T2brain.nii';
% threshoperation='>0';
ha=spm_vol(file);
a=(spm_read_vols(ha));
str=['a2=single(a' threshoperation ');'];
eval(str);
if ~exist('val1','var'); val1=1; end
if ~exist('val0','var'); val0=0; end
if isempty(val1); val1=1; end
if isempty(val0); val0=0; end
d=zeros(size(a2));
d(a2==1)=val1;
d(a2==0)=val0;
[pa fi ext]= fileparts(file);
if isempty(pa)
pa=pwd;
end
% fileout=fullfile(pa, [ fi '_msk' ext ]);
fileout=fullfile(pa, [ 'msk_' fi ext ]);
% [num2str(val2) num2str(val1)]
h=ha;
h.fname=fileout;
h.dt=[16 0];
h.descrip=['mask ' [num2str(val0) '-' num2str(val1)] ];
if ~exist('dowritefile','var'); dowritefile=0; end
if dowritefile==1
h=spm_create_vol(h);
h=spm_write_vol(h, d);
end
|
github
|
philippboehmsturm/antx-master
|
resize_img.m
|
.m
|
antx-master/mritools/various/resize_img.m
| 4,637 |
utf_8
|
f8ac6e8799481542156046e67e185665
|
function resize_img(imnames, Voxdim, BB, ismask)
% resize_img -- resample images to have specified voxel dims and BBox
% resize_img(imnames, voxdim, bb, ismask)
%
% Output images will be prefixed with 'r', and will have voxel dimensions
% equal to voxdim. Use NaNs to determine voxdims from transformation matrix
% of input image(s).
% If bb == nan(2,3), bounding box will include entire original image
% Origin will move appropriately. Use world_bb to compute bounding box from
% a different image.
%
% Pass ismask=true to re-round binary mask values (avoid
% growing/shrinking masks due to linear interp)
%
% See also voxdim, world_bb
% Based on John Ashburner's reorient.m
% http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7
% http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2
% Adapted by Ged Ridgway -- email bugs to [email protected]
% This version doesn't check spm_flip_analyze_images -- the handedness of
% the output image and matrix should match those of the input.
% Check spm version:
if exist('spm_select','file') % should be true for spm5
spm5 = 1;
elseif exist('spm_get','file') % should be true for spm2
spm5 = 0;
else
error('Can''t find spm_get or spm_select; please add SPM to path')
end
spm_defaults;
% prompt for missing arguments
if ( ~exist('imnames','var') || isempty(char(imnames)) )
if spm5
imnames = spm_select(inf, 'image', 'Choose images to resize');
else
imnames = spm_get(inf, 'img', 'Choose images to resize');
end
end
% check if inter fig already open, don't close later if so...
Fint = spm_figure('FindWin', 'Interactive'); Fnew = [];
if ( ~exist('Voxdim', 'var') || isempty(Voxdim) )
Fnew = spm_figure('GetWin', 'Interactive');
Voxdim = spm_input('Vox Dims (NaN for "as input")? ',...
'+1', 'e', '[nan nan nan]', 3);
end
if ( ~exist('BB', 'var') || isempty(BB) )
Fnew = spm_figure('GetWin', 'Interactive');
BB = spm_input('Bound Box (NaN => original)? ',...
'+1', 'e', '[nan nan nan; nan nan nan]', [2 3]);
end
if ~exist('ismask', 'var')
ismask = false;
end
if isempty(ismask)
ismask = false;
end
% reslice images one-by-one
vols = spm_vol(imnames);
for V=vols'
% (copy to allow defaulting of NaNs differently for each volume)
voxdim = Voxdim;
bb = BB;
% default voxdim to current volume's voxdim, (from mat parameters)
if any(isnan(voxdim))
vprm = spm_imatrix(V.mat);
vvoxdim = vprm(7:9);
voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim));
end
voxdim = voxdim(:)';
mn = bb(1,:);
mx = bb(2,:);
% default BB to current volume's
if any(isnan(bb(:)))
vbb = world_bb(V);
vmn = vbb(1,:);
vmx = vbb(2,:);
mn(isnan(mn)) = vmn(isnan(mn));
mx(isnan(mx)) = vmx(isnan(mx));
end
% voxel [1 1 1] of output should map to BB mn
% (the combination of matrices below first maps [1 1 1] to [0 0 0])
mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]);
% voxel-coords of BB mx gives number of voxels required
% (round up if more than a tenth of a voxel over)
imgdim = ceil(mat \ [mx 1]' - 0.1)';
% output image
VO = V;
[pth,nam,ext] = fileparts(V.fname);
VO.fname = fullfile(pth,['r' nam ext]);
VO.dim(1:3) = imgdim(1:3);
VO.mat = mat;
VO = spm_create_vol(VO);
spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed');
for i = 1:imgdim(3)
M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat);
img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp)
if ismask
img = round(img);
end
spm_write_plane(VO, img, i);
spm_progress_bar('Set', i)
end
spm_progress_bar('Clear');
end
% call spm_close_vol if spm2
if ~spm5
spm_close_vol(VO);
end
if (isempty(Fint) && ~isempty(Fnew))
% interactive figure was opened by this script, so close it again.
close(Fnew);
end
disp('Done.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bb = world_bb(V)
% world-bb -- get bounding box in world (mm) coordinates
d = V.dim(1:3);
% corners in voxel-space
c = [ 1 1 1 1
1 1 d(3) 1
1 d(2) 1 1
1 d(2) d(3) 1
d(1) 1 1 1
d(1) 1 d(3) 1
d(1) d(2) 1 1
d(1) d(2) d(3) 1 ]';
% corners in world-space
tc = V.mat(1:3,1:4)*c;
% bounding box (world) min and max
mn = min(tc,[],2)';
mx = max(tc,[],2)';
bb = [mn; mx];
|
github
|
philippboehmsturm/antx-master
|
rflipdim.m
|
.m
|
antx-master/mritools/various/rflipdim.m
| 2,357 |
utf_8
|
603851e90005962f28a211e5d94df714
|
function fileout=rflipdim(filename, dimorder, prefix )
%% flip dimensions/orientation and handendness/reflextion
% rflipdim(filename, dimorder, prefix )
% fileout=rflipdim(filename, dimorder, prefix )
%% IN
% filename : <str> filename
% dimorder : <3 val vector> [x y z] tp permute dims , use sign to flip handendness
% eg. [1 -3 2] x..x, y->z with fliped orientation, z->y
% prefix : <str> filename prefix , eg. 'p'
%% OUT
% fileout : name of file to write
%% example
% rflipdim('RwhsLabel_msk.nii', [1 3 -2], 'q' );
% rflipdim('RT2W.nii', [1 3 -2], 'q' );
% filename='T2brain_msk.nii'
if ~exist('prefix','var'); prefix='p'; end
if ~exist('dimorder','var')
prompt = {'order of dims,use[-] to flip dir of this dim, e.g. [1 3 -2], [] for orig. settup '};
dlg_title = 'Input for peaks function';
num_lines = 1;
def = {num2str([1 2 3])};
answer = inputdlg(prompt,dlg_title,num_lines,def);
dimorder=[str2num(char(answer)) ];
end
if length(dimorder)~=3; return; end
%===============================
flips=sign(dimorder);
perms=abs(dimorder);
[v d]=rgetnii(filename);
% v=spm_vol(st.overlay.fname)
% d=spm_read_vols(v); % r
isflip=find(flips==-1);
dia=diag(v.mat(1:3,1:3));
dc=zeros(3,1);
for i=1:length(isflip)
vsiz=dia(isflip(i));
a=[vsiz:vsiz:vsiz*(size(d,isflip(i))+1)]+v.mat(isflip(i),4);
%a=[0:vsiz:vsiz*(size(d,isflip)-1)]+v.mat(isflip(i),4);
dc(isflip(i))=-[a([ end]) ] ;
d=flipdim(d,isflip(i));
end
%permute
d=permute(d,[perms]);
% dsh=round(size(d)/2) ;
% subplot(3,3,7); imagesc( squeeze(d(dsh(1),: ,:) ) ) ;title(['2 3']);
% subplot(3,3,8); imagesc( squeeze(d(: ,dsh(2),:) ) ) ; title(['1 3']);
% subplot(3,3,9); imagesc( squeeze(d(: ,: ,dsh(3)) ) ); title(['1 2']);
%
%
v2=v;
[pa filename fmt]=fileparts(v2.fname);
v2.fname=fullfile(pa ,[prefix filename fmt]);
v2.dim=size(d);
mat=v2.mat;
dia=diag(mat);
mat(1:4+1:end)=dia([perms 4]);
orig=mat(1:3,4);
orig(find(dc~=0) )=dc(find(dc~=0));
% orig=orig.*flips'
% orig(2)=orig(2)+3
orig=orig(perms);
mat(:,4)=[orig; 1];
% mat(3,4)=mat(3,4)+2
v2.mat=mat;
spm_write_vol(v2, d); % write data to an image file.
fileout=v2.fname;
|
github
|
philippboehmsturm/antx-master
|
makegif.m
|
.m
|
antx-master/mritools/various/makegif.m
| 4,706 |
utf_8
|
889d5fdb8a3e5a1bc3c1e7a7a7e4de15
|
function makegif(fileoutname,ls,delay)
% ls={
% fullfile(pwd, 'v1.jpg')
% fullfile(pwd, 'v2.jpg')
% }
% makegif('test.gif',ls,.3);
loops=65535;
% delay=.4
for i=1:size(ls,1)
fi=ls{i};
if strcmpi('gif',fi(end-2:end))
[M c_map]=imread([fi]);
else
a=imread([fi]);
[M c_map]= rgb2ind(a,256);
end
% imwrite(M,c_map,[fout ],'gif','LoopCount',loops,'WriteMode','append','DelayTime',delay)
if i==1
imwrite(M,c_map,[fileoutname],'gif','LoopCount',loops,'DelayTime',delay);
else
imwrite(M,c_map,[fileoutname],'gif','WriteMode','append','DelayTime',delay);
end
end
return
%
%
%
%
%
%
%
%
%
%
%
%
%
% %
% %
% %
% %
% % clear all
% % [file_name file_path]=uigetfile({'*.jpeg;*.jpg;*.bmp;*.tif;*.tiff;*.png;*.gif','Image Files (JPEG, BMP, TIFF, PNG and GIF)'},'Select Images','multiselect','on');
% % file_name=sort(file_name);
% % [file_name2 file_path2]=uiputfile('*.gif','Save as animated GIF',file_path);
% % lps=questdlg('How many loops?','Loops','Forever','None','Other','Forever');
% % switch lps
% % case 'Forever'
% % loops=65535;
% % case 'None'
% % loops=1;
% % case 'Other'
% % loops=inputdlg('Enter number of loops? (must be an integer between 1-65535) .','Loops');
% % loops=str2num(loops{1});
% % end
% %
% % delay=inputdlg('What is the delay time? (in seconds) .','Delay');
% % delay=str2num(delay{1});
% % dly=questdlg('Different delay for the first image?','Delay','Yes','No','No');
% % if strcmp(dly,'Yes')
% % delay1=inputdlg('What is the delay time for the first image? (in seconds) .','Delay');
% % delay1=str2num(delay1{1});
% % else
% % delay1=delay;
% % end
% % dly=questdlg('Different delay for the last image?','Delay','Yes','No','No');
% % if strcmp(dly,'Yes')
% % delay2=inputdlg('What is the delay time for the last image? (in seconds) .','Delay');
% % delay2=str2num(delay2{1});
% % else
% % delay2=delay;
% % end
% %
% % h = waitbar(0,['0% done'],'name','Progress') ;
% % for i=1:length(file_name)
% % if strcmpi('gif',file_name{i}(end-2:end))
% % [M c_map]=imread([file_path,file_name{i}]);
% % else
% % a=imread([file_path,file_name{i}]);
% % [M c_map]= rgb2ind(a,256);
% % end
% % if i==1
% % imwrite(M,c_map,[file_path2,file_name2],'gif','LoopCount',loops,'DelayTime',delay1)
% % elseif i==length(file_name)
% % imwrite(M,c_map,[file_path2,file_name2],'gif','WriteMode','append','DelayTime',delay2)
% % else
% % imwrite(M,c_map,[file_path2,file_name2],'gif','WriteMode','append','DelayTime',delay)
% % end
% % waitbar(i/length(file_name),h,[num2str(round(100*i/length(file_name))),'% done']) ;
% % end
% % close(h);
% % msgbox('Finished Successfully!')
% %
% %
% %
% %
% %
% %
% %
% %
% %
% %
% %
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
% ls={
% fullfile(pwd, 'm1.png')
% fullfile(pwd, 'm2.png')
% fullfile(pwd, 'm1.png')
% fullfile(pwd, 'm2.png')
% }
%
% clear im
%
% for i=1:size(ls,1)
% [a m]=imread(ls{i});
%
% [im2,map] = rgb2ind(a,256,'nodither');
% % if i==2
% map2=map
% % end
% im(:,:,:,i)=im2 ;%rgb2ind(f.cdata,map,'nodither');
% end
% imwrite(im,map2,'test.gif','DelayTime',1,'LoopCount',inf) %g443800
%
%
% %% How to make an animated GIF
% % This example animates the vibration of a membrane, captures a series of
% % screen shots, and saves the animation as a GIF image file.
% %
% % Copyright 2008-2010 The MathWorks, Inc.
% %%
% % <<../DancingPeaks.gif>>
% %%
% % The resulted animated GIF was embedded in this HTML page using the Image
% % cell markup (see
% % <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/f6-30186.html#breug1i help for markup formatting>).
% %%
% % Here's the M code.
% Z = peaks;
% surf(Z)
% axis tight
% set(gca,'nextplot','replacechildren','visible','off')
% f = getframe;
% [im,map] = rgb2ind(f.cdata,256,'nodither');
% im(1,1,1,20) = 0;
% for k = 1:20
% surf(cos(2*pi*k/20)*Z,Z)
% f = getframe;
% im(:,:,1,k) = rgb2ind(f.cdata,map,'nodither');
% end
% imwrite(im,map,'DancingPeaks.gif','DelayTime',0,'LoopCount',inf) %g443800
% %%
% % For more details about GIF settings |DelayTime| and |LoopCount| for desired
% % effect see the
% % <http://www.mathworks.com/access/helpdesk/help/techdoc/ref/imwrite.html#f25-752355 help for |imwrite/gif|>.
|
github
|
philippboehmsturm/antx-master
|
resize_img3.m
|
.m
|
antx-master/mritools/various/resize_img3.m
| 5,527 |
utf_8
|
02908961fff334c7f44f76bb28bf77cd
|
function outfile=resize_img3(imnames, Voxdim, BB, ismask, interpmethod,prefix, dt)
% function outfile=resize_img3(imnames, Voxdim, BB, ismask, interpmethod,prefix, dt)
% resize_img2 -- resample images to have specified voxel dims and BBox
% resize_img2(imnames, voxdim, bb, ismask,interpmethod)
% outfile: filename written
% Output images will be prefixed with 'r', and will have voxel dimensions
%
% prefix: if prefix has format-end (.nii)-->file will be saves as such
% -->instead of prefix
% equal to voxdim. Use NaNs to determine voxdims from transformation matrix
% of input image(s).
% If bb == nan(2,3), bounding box will include entire original image
% Origin will move appropriately. Use world_bb to compute bounding box from
% a different image.
% interpmethod: 0/1.. : NN/linear... see SPM
%
% Pass ismask=true to re-round binary mask values (avoid
% growing/shrinking masks due to linear interp)
%
% See also voxdim, world_bb
% Based on John Ashburner's reorient.m
% http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7
% http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2
% Adapted by Ged Ridgway -- email bugs to [email protected]
% This version doesn't check spm_flip_analyze_images -- the handedness of
% the output image and matrix should match those of the input.
% Check spm version:
if exist('spm_select','file') % should be true for spm5
spm5 = 1;
elseif exist('spm_get','file') % should be true for spm2
spm5 = 0;
else
error('Can''t find spm_get or spm_select; please add SPM to path')
end
spm_defaults;
% prompt for missing arguments
if ( ~exist('imnames','var') || isempty(char(imnames)) )
if spm5
imnames = spm_select(inf, 'image', 'Choose images to resize');
else
imnames = spm_get(inf, 'img', 'Choose images to resize');
end
end
% check if inter fig already open, don't close later if so...
Fint = spm_figure('FindWin', 'Interactive'); Fnew = [];
if ( ~exist('Voxdim', 'var') || isempty(Voxdim) )
Fnew = spm_figure('GetWin', 'Interactive');
Voxdim = spm_input('Vox Dims (NaN for "as input")? ',...
'+1', 'e', '[nan nan nan]', 3);
end
if ( ~exist('BB', 'var') || isempty(BB) )
Fnew = spm_figure('GetWin', 'Interactive');
BB = spm_input('Bound Box (NaN => original)? ',...
'+1', 'e', '[nan nan nan; nan nan nan]', [2 3]);
end
if ~exist('ismask', 'var')
ismask = false;
end
if isempty(ismask)
ismask = false;
end
% reslice images one-by-one
vols = spm_vol(imnames);
for V=vols'
% (copy to allow defaulting of NaNs differently for each volume)
voxdim = Voxdim;
bb = BB;
% default voxdim to current volume's voxdim, (from mat parameters)
if any(isnan(voxdim))
vprm = spm_imatrix(V.mat);
vvoxdim = vprm(7:9);
voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim));
end
voxdim = voxdim(:)';
mn = bb(1,:);
mx = bb(2,:);
% default BB to current volume's
if any(isnan(bb(:)))
vbb = world_bb(V);
vmn = vbb(1,:);
vmx = vbb(2,:);
mn(isnan(mn)) = vmn(isnan(mn));
mx(isnan(mx)) = vmx(isnan(mx));
end
% voxel [1 1 1] of output should map to BB mn
% (the combination of matrices below first maps [1 1 1] to [0 0 0])
mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]);
% voxel-coords of BB mx gives number of voxels required
% (round up if more than a tenth of a voxel over)
imgdim = ceil(mat \ [mx 1]' - 0.1)';
%===============================================
VO = V;
[pth,nam,ext] = fileparts(V.fname);
if isempty(prefix);
prefix='r';
VO.fname = fullfile(pth,[prefix nam ext]);
else
[pa2 fi2 ext2]=fileparts(prefix);
if isempty(ext2) %%PREFIX
% prefix='r';
VO.fname = fullfile(pth,[prefix nam ext]);
else %% NEW NAME
VO.fname = prefix;
end
end
if exist('dt') && length(dt)==2
VO.dt =dt;
end
% output image
VO.dim(1:3) = imgdim(1:3);
VO.mat = mat;
VO = spm_create_vol(VO);
spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed');
for i = 1:imgdim(3)
M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat);
% img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp)
img = spm_slice_vol(V, M, imgdim(1:2), interpmethod); % (linear interp)
if ismask
img = round(img);
end
spm_write_plane(VO, img, i);
spm_progress_bar('Set', i)
end
spm_progress_bar('Clear');
end
% call spm_close_vol if spm2
if ~spm5
spm_close_vol(VO);
end
if (isempty(Fint) && ~isempty(Fnew))
% interactive figure was opened by this script, so close it again.
close(Fnew);
end
disp('Done.')
outfile=VO.fname;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bb = world_bb(V)
% world-bb -- get bounding box in world (mm) coordinates
d = V.dim(1:3);
% corners in voxel-space
c = [ 1 1 1 1
1 1 d(3) 1
1 d(2) 1 1
1 d(2) d(3) 1
d(1) 1 1 1
d(1) 1 d(3) 1
d(1) d(2) 1 1
d(1) d(2) d(3) 1 ]';
% corners in world-space
tc = V.mat(1:3,1:4)*c;
% bounding box (world) min and max
mn = min(tc,[],2)';
mx = max(tc,[],2)';
bb = [mn; mx];
|
github
|
philippboehmsturm/antx-master
|
rsavenii.m
|
.m
|
antx-master/mritools/various/rsavenii.m
| 702 |
utf_8
|
6aa028e96e3f3f5bdc80b3e351cc5c09
|
function filenameout=rsavenii(filename,h,d, dt)
%% save Nifti
% filenameout=rsavenii(filename,h,d, dt)
% rsavenii(filename,h,d)
% filenameout=rsavenii(filename,h,d)
%% in
% filename: filename to save (.nii not needed)
% h : header -->fname is replaced by new filename
% d : data
%% out
% filenameout : written filename
%% example
% rsavenii('test',h,d )
% rsavenii('test2.nii',h,d )
[pa fi ext]= fileparts(filename);
% if isempty(pa); pa=''; end
if isempty(ext); ext='.nii'; end
h.fname=fullfile(pa,[ fi ext]);
if exist('dt')==1 && length(dt)==2
h.dt=dt;
end
h=spm_create_vol(h);
h=spm_write_vol(h, d);
filenameout=h.fname;
|
github
|
philippboehmsturm/antx-master
|
gifoverlay.m
|
.m
|
antx-master/mritools/various/gifoverlay.m
| 1,751 |
utf_8
|
53e7d70a2973772ff8e6087c3c7c16ac
|
%% simple check overlay
function gifoverlay(t1,t2,outname,resol, interpx ,strtag)
% pathdata='C:\Dokumente und Einstellungen\skoch\Desktop\allenAtlas\MBAT_WHS_atlas_v0.6.2\MBAT_WHS_atlas_v0.6.2\Data'
pathdata=pwd;
% [t,sts] = spm_select(inf,'dir','SEGMENTATION select Directories','',pathdata,'.*');
% if isempty(t);
% disp('no folders selected');
% return
% end
% paths=cellstr(t);
%
% %% loop through
%
% [t1] = spm_select('FPList',[paths{i} ],'^s.*nii$') ; %t1 =cellstr(t);
% % [t2] = spm_select('FPList',[paths{i} ],'W*.*nii$') ;% t2 =cellstr(t);
% [t2]=spm_select
ls={t1; t2 };
paout= (pathdata );
if ~exist('interpx')
interpx=1;
end
if ~exist('strtag')
strtag='';
end
[h ad]=ovlAtlas(ls,interpx,strtag);
figure(gcf);
if 1
% resol='-r300'
print(gcf,'-djpeg',resol,fullfile(paout, 'vv1.jpg'));
delete(h);
% ad(ad~=0)=0;
% ad(ad==0)=0;
% set(h, 'AlphaData', ad);
figure(gcf);
drawnow;pause(.1);
print(gcf,'-djpeg',resol,fullfile(paout, 'vv2.jpg'));
end
%%*****************************************
if 1
[pa fi]= fileparts(t1);
ls2={
fullfile(paout, 'vv1.jpg');
fullfile(paout, 'vv2.jpg');
};
% makegif(fullfile(paout, [outname '.gif']) ,ls2,.3);
% makegif(fullfile(paout, [outname '.gif']) ,ls2,.3);
%
[pa fi]=fileparts(outname);
makegif(fullfile(pa, [fi '.gif']) ,ls2,.3);
delete(paout, 'vv1.jpg');
delete(paout, 'vv2.jpg');
end
% close all
|
github
|
philippboehmsturm/antx-master
|
simpleoverlay.m
|
.m
|
antx-master/mritools/various/simpleoverlay.m
| 7,368 |
utf_8
|
21f57de2dffa3c1bf1157ad4da6b78fb
|
function h=simpleoverlay(ls, slices, tresh, col )
% simpleoverlay(ls2, [4 8 9], tresh,{'g','m' } );
% cf;
% clear
if 0
ls3={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
'c2s20150908_FK_C1M04_1_3_1.nii'
'c3s20150908_FK_C1M04_1_3_1.nii'
}
ls2={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
'c2s20150908_FK_C1M04_1_3_1.nii'
}
ls1={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
}
slices=1:32
tresh=.01
end
if exist('col')
col=colorcheck(col)
end
%% ==============================
if isempty(slices)
h1=spm_vol(ls{1});
slices=1:h1.dim(3);
end
for i=1:size(ls,1)
h1=spm_vol(ls{i});
dum=single(spm_read_vols(h1));
dum=dum(:,:,slices);
dum=flipdim(permute(dum,[2 1 3]),1);
if i==1
x=single(zeros([size(dum) size(ls,1) ])) ;
end
x(:,:,:,i)=dum;
end
for i=1:size(x,3)
dum= mat2gray(x(:,:,i,1));
dum=brighten( imadjust(dum),.7);
x(:,:,i,1)=medfilt2(dum);
% cc2(:,:,i)= mat2gray(c2(:,:,i));
% cc3(:,:,i)= mat2gray(c3(:,:,i));
end
for i=1:size(x,4)
xm(:,:,i)=createMontageImage(permute(x(:,:,:,i),[1 2 4 3]));
end
ana=xm(:,:,1);
xm=xm(:,:,2:end) ;
h=figure('color','w');
imagesc( ana(:,:,[1 1 1]) );
% imagesc( xm(:,:,[1 1 1]) );
hold on;
% tresh=.01
xv=xm.*nan;
for i=1:size(xm,3)
b2=xm(:,:,i);
t1 = b2 .* ( b2 >= tresh & b2 <= 1.0 ); % threshold second image
t1(t1>0)=i;
xv(:,:,i)=t1;
end
ts =sum(xv,3);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts, 'tag','myIMAGE');colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
if exist('col')==0
col={[0 0 1] [1 0 0] [0 1 0] [ 1 1 0] [0 1 1] [1 0 1]};
end
n=size(xv,3)
% cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
cmap=cell2mat(col(1:n)');
try; cmap(end+1,:)=sum(cmap(1:2,:));end
try; cmap(end+1,:)=[0.7490 0 0.7490];end
if n==1; n2=1;end
if n==2; n2=3;end
if n==3; n2=6;end
cmap=cmap(1:n2,:);
if n==1; cmap=[cmap;cmap]; n2=2; end
colormap(cmap);
hb=colorbar;
caxis([1 n2]);
set(gca,'position',[0 0 1 1]);
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w');
function col=colorcheck(col)
cr={ 'b' [1 0 0]
'g' [0 .5 0]
'r' [1 0 0]
'c' [0 1 1]
'm' [1 0 1]
'y' [1 1 0]
'k' [0 0 0]
'w' [1 1 1] }
for i=1:size(cr,1)
ix= find(strcmp(col,cr{i,1}) );
if ~isempty(ix)
col{ ix} =cr{i,2}
end
end
% b blue . point - solid
% g green o circle : dotted
% r red x x-mark -. dashdot
% c cyan + plus -- dashed
% m magenta * star (none) no line
% y yellow s square
% k black d diamond
% w white v triangle (down)
% ^ triangle (up)
% < triangle (left)
% > triangle (right)
% p pentagram
% h hexagram
%
return
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
col={[0 0 1] [1 0 0] };
n=2
cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
colormap(cmap)
hb=colorbar
caxis([1 2])
set(gca,'position',[0 0 1 1])
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w')
% print('-djpeg','-r200','muell.jpg')
if 0
print('-djpeg','-r300','v2.jpg')
set( ih, 'AlphaData', talph/100 );
print('-djpeg','-r300','v1.jpg')
end
%%*****************************************
if 0
ls={
fullfile(pwd, 'v1.jpg')
fullfile(pwd, 'v2.jpg')
}
makegif('test3.gif',ls,.3);
end
% 00000000000000000000000000000000000000000000000000000000000
return
clear
h1=spm_vol('s.nii')
h2=spm_vol('c1.nii')
h3=spm_vol('c2.nii')
cc1=spm_read_vols(h1);
cc2=spm_read_vols(h2);
cc3=spm_read_vols(h3);
cc1=single(cc1);
cc2=single(cc2);
cc3=single(cc3);
slices=1:2:size(cc1,3)
cc1=cc1(:,:,slices);
cc2=cc2(:,:,slices);
cc3=cc3(:,:,slices);
%shiftDIM
cc1=flipdim(permute(cc1,[2 1 3]),1);
cc2=flipdim(permute(cc2,[2 1 3]),1);
cc3=flipdim(permute(cc3,[2 1 3]),1);
%% run2
for i=1:size(cc1,3)
dum= mat2gray(cc1(:,:,i));
dum=brighten( imadjust(dum),.7);
cc1(:,:,i)=medfilt2(dum);
% cc2(:,:,i)= mat2gray(c2(:,:,i));
% cc3(:,:,i)= mat2gray(c3(:,:,i));
end
% montage(permute(cc1,[1 2 4 3]))
a1=createMontageImage(permute(cc1,[1 2 4 3]));
b2=createMontageImage(permute(cc2,[1 2 4 3]));
b3=createMontageImage(permute(cc3,[1 2 4 3]));
fg
imagesc( a1(:,:,[1 1 1]) );
hold on;
% freezeColors
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
col={[0 0 1] [1 0 0] }
n=2
cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
colormap(cmap)
hb=colorbar
caxis([1 2])
set(gca,'position',[0 0 1 1])
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w')
% print('-djpeg','-r200','muell.jpg')
% print('-djpeg','-r200','v2.jpg')
%%*****************************************
return
h1=spm_vol('s.nii')
h2=spm_vol('c1.nii')
h3=spm_vol('c2.nii')
c1=spm_read_vols(h1);
c2=spm_read_vols(h2);
c3=spm_read_vols(h3);
alpha=.2
out2=nan.*c1;;
fg
for i=8%:size(c1,3)
b1=c1(:,:,10+i);
b2=c2(:,:,10+i);
b3=c3(:,:,10+i);
% out =dum(b1,b2,b2,.5, alpha);
% % subplot(4,3,i);
% image(out);
% axis('image');
% out2(:,:,i)=out;
end
%
% figure;
% imshow( first(:,:,[1 1 1]) ); % make the first a grey-scale image with three channels so it will not be affected by the colormap later on
% hold on;
% t_second = second .* ( second >= .6 & second <= 1.0 ); % threshold second image
% ih = imshow( t_second );
% set( ih, 'AlphaData', t_second );
% colormap jet
%% run
% b1=flipud(b1);
figure;
% b11=mat2gray(b1);
b11=brighten( imadjust(mat2gray(b1)),.7);
b11 = medfilt2(b11);
imagesc( b11(:,:,[1 1 1]) );
% imagesc( b1(:,:,[1 1 1]) ); % make the first a grey-scale image with three channels so it will not be affected by the colormap later on
% imagesc(b1);colormap gray
hold on;
% freezeColors
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
% talph(:,1:2:end)=0;
set( ih, 'AlphaData', talph );
colormap jet
'a'
|
github
|
philippboehmsturm/antx-master
|
ovl.m
|
.m
|
antx-master/mritools/various/ovl.m
| 1,153 |
utf_8
|
20bb1691c9a3be16cdfb376efa5ecada
|
function ovl( v1,v2, interpx, name2write,infos )
if ~exist('name2write','var')
name2write='ztest';
end
num=length(dir([ name2write '*.txt']));
if isempty(num)
name=[ name2write '1' '.txt'] ;%'ztest1'
else
% name=['ztest' num2str(num+1)]
name=[ name2write num2str(num+1) '.txt'] ;%'ztest1'
end
% gifoverlay('testsample_orient_s20150908_FK_C1M01_1_3_1.nii',...
% 'WAR1_pRWHS_0.6.1_Labels.nii',name,'-r300')
if ~exist('interpx'); interpx=1; end
gifoverlay(v1,...
v2,name,'-r300',interpx) ;
delete('vv1.jpg');delete('vv2.jpg');
try
%% ##1
% job_id = spm_jobman('interactive',m)
%% ##2
% char(gencode(m)')
%% ##3
% ha=findobj(0,'tag','module');
% str=((get(ha,'string')))
%% ##4
if exist('infos')
if iscell(infos)
str2=(gencode(infos)');
else
str2=infos;
end
% str2=regexprep(str,' ','')
%str2=char(regexprep(str,' ','_'))
pwrite2file([strrep(name,'.txt','') '.txt'],str2)
end
end
end
|
github
|
philippboehmsturm/antx-master
|
resize_img5.m
|
.m
|
antx-master/mritools/various/resize_img5.m
| 5,686 |
utf_8
|
23757070256aa23ec8d847669220cf5c
|
function outfile=resize_img5(imname,outname, Voxdim, BB, ismask, interpmethod, dt)
%% resample images to have specified voxel dims and BBox, NewName with suffix, optional: dt(numeric class)
% function outfile=resize_img5(imname,outname, Voxdim, BB, ismask, interpmethod, dt)
% resize_img2 -- resample images to have specified voxel dims and BBox
% resize_img2(imname, voxdim, bb, ismask,interpmethod)
% outfile: filename written
% Output images will be prefixed with 'r', and will have voxel dimensions
%
% suffix: if suffix has format-end (.nii)-->file will be saves as such
% -->instead of suffix
% equal to voxdim. Use NaNs to determine voxdims from transformation matrix
% of input image(s).
% If bb == nan(2,3), bounding box will include entire original image
% Origin will move appropriately. Use world_bb to compute bounding box from
% a different image.
% interpmethod: 0/1.. : NN/linear... see SPM
%
% Pass ismask=true to re-round binary mask values (avoid
% growing/shrinking masks due to linear interp)
%
% See also voxdim, world_bb
% Based on John Ashburner's reorient.m
% http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7
% http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2
% Adapted by Ged Ridgway -- email bugs to [email protected]
% This version doesn't check spm_flip_analyze_images -- the handedness of
% the output image and matrix should match those of the input.
% Check spm version:
if exist('spm_select','file') % should be true for spm5
spm5 = 1;
elseif exist('spm_get','file') % should be true for spm2
spm5 = 0;
else
error('Can''t find spm_get or spm_select; please add SPM to path')
end
spm_defaults;
% prompt for missing arguments
if ( ~exist('imname','var') || isempty(char(imname)) )
if spm5
imname = spm_select(inf, 'image', 'Choose images to resize');
else
imname = spm_get(inf, 'img', 'Choose images to resize');
end
end
% check if inter fig already open, don't close later if so...
Fint = spm_figure('FindWin', 'Interactive'); Fnew = [];
if ( ~exist('Voxdim', 'var') || isempty(Voxdim) )
Fnew = spm_figure('GetWin', 'Interactive');
Voxdim = spm_input('Vox Dims (NaN for "as input")? ',...
'+1', 'e', '[nan nan nan]', 3);
end
if ( ~exist('BB', 'var') || isempty(BB) )
Fnew = spm_figure('GetWin', 'Interactive');
BB = spm_input('Bound Box (NaN => original)? ',...
'+1', 'e', '[nan nan nan; nan nan nan]', [2 3]);
end
if ~exist('ismask', 'var')
ismask = false;
end
if isempty(ismask)
ismask = false;
end
% reslice images one-by-one
vols = spm_vol(imname);
for V=vols'
% (copy to allow defaulting of NaNs differently for each volume)
voxdim = Voxdim;
bb = BB;
% default voxdim to current volume's voxdim, (from mat parameters)
if any(isnan(voxdim))
vprm = spm_imatrix(V.mat);
vvoxdim = vprm(7:9);
voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim));
end
voxdim = voxdim(:)';
mn = bb(1,:);
mx = bb(2,:);
% default BB to current volume's
if any(isnan(bb(:)))
vbb = world_bb(V);
vmn = vbb(1,:);
vmx = vbb(2,:);
mn(isnan(mn)) = vmn(isnan(mn));
mx(isnan(mx)) = vmx(isnan(mx));
end
% voxel [1 1 1] of output should map to BB mn
% (the combination of matrices below first maps [1 1 1] to [0 0 0])
mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]);
% voxel-coords of BB mx gives number of voxels required
% (round up if more than a tenth of a voxel over)
imgdim = ceil(mat \ [mx 1]' - 0.1)';
%===============================================
VO = V;
[pth,nam,ext] = fileparts(V.fname);
% if isempty(suffix);
% suffix='r';
% VO.fname = fullfile(pth,[ nam suffix ext]);
% else
% [pa2 fi2 ext2]=fileparts(suffix);
% if isempty(ext2) %%PREFIX
% % suffix='r';
% VO.fname = fullfile(pth,[ nam suffix ext]);
% else %% NEW NAME
% VO.fname = suffix;
% end
% end
VO.fname=outname;
if exist('dt')==1
if length(dt)==2
VO.dt =dt;
end
end
% output image
VO.dim(1:3) = imgdim(1:3);
VO.mat = mat;
VO = spm_create_vol(VO);
spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed');
for i = 1:imgdim(3)
M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat);
% img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp)
img = spm_slice_vol(V, M, imgdim(1:2), interpmethod); % (linear interp)
if ismask
img = round(img);
end
spm_write_plane(VO, img, i);
spm_progress_bar('Set', i)
end
spm_progress_bar('Clear');
end
% call spm_close_vol if spm2
if ~spm5
spm_close_vol(VO);
end
if (isempty(Fint) && ~isempty(Fnew))
% interactive figure was opened by this script, so close it again.
close(Fnew);
end
%disp('Done.')
outfile=VO.fname;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bb = world_bb(V)
% world-bb -- get bounding box in world (mm) coordinates
d = V.dim(1:3);
% corners in voxel-space
c = [ 1 1 1 1
1 1 d(3) 1
1 d(2) 1 1
1 d(2) d(3) 1
d(1) 1 1 1
d(1) 1 d(3) 1
d(1) d(2) 1 1
d(1) d(2) d(3) 1 ]';
% corners in world-space
tc = V.mat(1:3,1:4)*c;
% bounding box (world) min and max
mn = min(tc,[],2)';
mx = max(tc,[],2)';
bb = [mn; mx];
|
github
|
philippboehmsturm/antx-master
|
rreslice2.m
|
.m
|
antx-master/mritools/various/rreslice2.m
| 1,188 |
utf_8
|
ffc68580982585de41ce5433f46ecb3f
|
function [h d]=rreslice2(VI,mat,hld)
% VI: hdr
% mat: mat
% hld:interpolation method.
% FORMAT reslice(PI,PO,dim,mat,hld)
% PI - input filename
% PO - output filename
% dim - 1x3 matrix of image dimensions
% mat - 4x4 affine transformation matrix mapping
% from vox to mm (for output image).
% To define M from vox and origin, then
% off = -vox.*origin;
% M = [vox(1) 0 0 off(1)
% 0 vox(2) 0 off(2)
% 0 0 vox(3) off(3)
% 0 0 0 1];
%
% hld - interpolation method.
%___________________________________________________________________________
% @(#)JohnsGems.html 1.42 John Ashburner 05/02/02
% VI = spm_vol(PI);
VO = VI;
VO.fname = 'mist';
VO.mat = mat;
% VO.dim(1:3) = dim;
v2=single(zeros(VO.dim));
% VO = spm_create_image(VO); end;
for x3 = 1:VO.dim(3),
M = inv(spm_matrix([0 0 -x3 0 0 0 1 1 1])*inv(VO.mat)*VI.mat);
v = spm_slice_vol(VI,M,VO.dim(1:2),hld);
% VO = spm_write_plane(VO,v,x3);
v2(:,:,x3)=v;
end;
h=VO;
d=v2;
|
github
|
philippboehmsturm/antx-master
|
rapplymask.m
|
.m
|
antx-master/mritools/various/rapplymask.m
| 1,988 |
utf_8
|
71794c65b5cadd9efa897af6bc77ae6e
|
function [fileout h x ]=rapplymask(file,filemsk,threshoperation, val1, val0, suffix )
%% apply maskFile to another file
% [fileout h x ]=rapplymask(file,filemsk,threshoperation, val1, val0, suffix )
%% In
% file : file
% filemsk : masking file
% threshoperation: string (operation&value) , e.g '>0' ,'>=1.24'
% val1: value to replace trueValues (ones) , e.g 3, 1000...
% val0: value to replace falseValues (zeros) , e.g nan, inf..-1000
% suffix: string to append ; default: '_msked'
% dowritefile : [0,1]..no/jes
%% out:
% fileout/h/x ..written filename/header/data
%% example
% [fileout h x]=rapplymask('RE_rfNt2.nii','RE_rfNat.nii','>0',1,nan,'_masked');
% [fileout h x ]=rapplymask('RE_s20150908_FK_C1M01_1_3_1.nii ','RE_msk_brain.nii','>0',1,nan,'_masked');
if 0
file ='RE_rfNt2.nii'
filemsk='RE_rfNat.nii'
threshoperation='>0'
val0=nan
suffix='_masked'
[fileout h d ]=rapplymask('RE_rfNt2.nii','RE_rfNat.nii','>0',1,nan,'_masked')
end
ha=spm_vol(filemsk);
a=(spm_read_vols(ha));
str=['a2=single(a' threshoperation ');'];
eval(str);
if ~exist('val1','var'); val1=1; end
if ~exist('val0','var'); val0=0; end
if ~exist('suffix','var'); suffix='_msked'; end
if isempty(val1); val1=1; end
if isempty(val0); val0=0; end
if isempty(suffix); suffix='_msked'; end
d=zeros(size(a2));
d(a2==1)=val1;
d(a2==0)=val0;
%% applyMASK
hb=spm_vol(file);
b=(spm_read_vols(hb));
x=b.*d;
[pa fi ext]= fileparts(file);
if isempty(pa)
pa=pwd;
end
% fileout=fullfile(pa, [ fi '_msk' ext ]);
fileout=fullfile(pa, [ fi suffix ext ]);
% [num2str(val2) num2str(val1)]
h=hb;
h.fname=fileout;
if any(isnan(unique(x(:))))
h.dt=[16 0];
end
h.descrip=['masked ' [num2str(val0) '-' num2str(val1)] ];
% if ~exist('dowritefile','var'); dowritefile=0; end
% if dowritefile==1
h=spm_create_vol(h);
h=spm_write_vol(h, x);
% end
|
github
|
philippboehmsturm/antx-master
|
makebrainmask3.m
|
.m
|
antx-master/mritools/various/makebrainmask3.m
| 1,815 |
utf_8
|
d27a6b8abffc9ce0c5646aaf7368f1b9
|
function makebrainmask3(tpm, thresh, outfilename)
%% make brain mask from TPM
% tpm: cellaray with 2 or 3 or x compartiments
% tpm= { 'wc1T2.nii' 'wc2T2.nii' 'wc3T2.nii'}'
% tpm= { 'wc1T2.nii' 'wc2T2.nii' }';
% tpm=fullpath(pwd,tpm);
% makebrainmask2(tpm, thresh, 'test1.nii')
% thresh=.2;
for i=1:length(tpm);
[h1 d1 xyz xyzind]=rgetnii(tpm{i});
if i==1
dm=d1.*0;
end
dm=dm+single((d1>=thresh));
end
dm=dm>.5;
%% cluster data-----
dm3=dm(:);
idx=find(dm3==1);
index=xyzind(:,idx);
[A ] = spm_clusters(index);
tab=tabulate(A);
clmax=find(tab(:,2)==max(tab(:,2)));
idx2=find(A==clmax);
% idx2=find(A==1);
idx4=idx(idx2);
dm4=dm3.*0;
dm4(idx4)=1;
dm5=reshape(dm4,(h1.dim));
dm=dm5;
%% fill holes (over 3d volume does not work accurately -->slieceWise)
df=dm;
for i=1:size(df,3)
df(:,:,i)= imfill(df(:,:,i),'holes') ;
end
%
%
% %
%
% df2=df.*0;
% for i=1:size(df,3)
% BW=df(:,:,i);
% [B,L] = bwboundaries(BW,4,'noholes');
% % [L,num] = bwlabel(BW,4)
%
%
% num=cell2mat(cellfun(@(x) {size(x,1)} ,B));
% delthresh=.25;
% pnum=num.*100./(sum(num));
% isurv=find(pnum>(delthresh*100));
%
% L2=L.*0;
% for k=1:length(isurv)
% L2( L==isurv(k) )=1;
% end
% df2(:,:,i)=L2;
%
%
% % fg(14);cla
% % imagesc(label2rgb(L, @jet, [.5 .5 .5]));
% % hold on
% % for k = 1:length(isurv)
% % boundary = B{isurv(k)};
% % plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)
% % end
% % title(i);
% % drawnow
% % pause
% end
df2=df;
%----------
h2=h1;
h2.dt=[2 0];
rsavenii(outfilename,h2,df2 );
|
github
|
philippboehmsturm/antx-master
|
rgetnii.m
|
.m
|
antx-master/mritools/various/rgetnii.m
| 582 |
utf_8
|
f16d21c0e69ea77e7fa9ad3a565430e7
|
function [h d xyz xyzind]=rgetnii(file )
%% get Nifti/analyzeFormat
% [h d xyz xyzind]=rgetnii(file )
%% in
% file: filename ; e.g. 'T2brain.nii';
%% out
%[h d xyz]: header,data,xyz
%% example
% [h d xyz]=rgetnii('T2brain.nii')
% [pa fi ext]=fileparts(file)
% if strcmp(ext,'.gz')
% fname=gunzip(file)
% end
h=spm_vol(file);
if nargout<=2;
[d ]=(spm_read_vols(h));
elseif nargout==3
[d xyz]=(spm_read_vols(h));
elseif nargout==4
[d xyz]=(spm_read_vols(h));
[x y z] = ind2sub(size(d),1:length(d(:)));
xyzind=[x;y;z];
end
|
github
|
philippboehmsturm/antx-master
|
simpleoverlay2.m
|
.m
|
antx-master/mritools/various/simpleoverlay2.m
| 9,360 |
utf_8
|
c0ff2ff6e8acc61d2ddc0082e80484fc
|
function simpleoverlay(ls, slices, tresh, col,dirs, olap )
% simpleoverlay(ls2, [4 8 9], tresh,{'g','m' } );
% simpleoverlay2(ls, [], .002,{'r','m' },0 );
% simpleoverlay2(ls, [], .002,{'r','g' },0 );
% simpleoverlay2({t2file; TPMpathnew{2}},'5',.01,{'r'},4.9);
% simpleoverlay2({t2file; TPMpathnew{2}},[],.01,{'r'},4.9);
% cf;
% clear
if 0
ls3={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
'c2s20150908_FK_C1M04_1_3_1.nii'
'c3s20150908_FK_C1M04_1_3_1.nii'
}
ls2={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
'c2s20150908_FK_C1M04_1_3_1.nii'
}
ls1={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
}
slices=1:32
tresh=.01
end
if exist('col')
col=colorcheck(col)
end
%% ==============================
if isempty(slices)
h1=spm_vol(ls{1});
slices=1:h1.dim(3);
end
for i=1:size(ls,1)
h1=spm_vol(ls{i});
if i==1
href=h1;
dum=single(spm_read_vols(h1));
else
% 'a'
inhdr = spm_vol(ls{i}); %load header
inimg = spm_read_vols(inhdr); %load volume
tarhdr = href;%spm_vol(ls{2}); %load header
[outhdr,outimg] = nii_reslice_target(inhdr,inimg, tarhdr); %resize in memory
dum=outimg;
end
if ischar(slices) %'2' or '5'-->use every 2nd,5th slice
slicespace=str2num(slices)
slices=1:slicespace:size(dum,1);
end
dum=dum(:,:,slices);
dum=dum./max(dum(:));
% dum=flipdim(permute(dum,[2 1 3]),1);
% if dirs==1
% dum=permute(dum,[1 3 2 ]);
% elseif dirs==2
% dum=permute(dum,[2 1 3 ]);
% elseif dirs==3
% dum=permute(dum,[3 2 1 ]);
% end
if i==1
x=single(zeros([size(dum) size(ls,1) ])) ;
end
x(:,:,:,i)=dum;
end
for i=1:size(x,3)
dum= mat2gray(x(:,:,i,1));
dum=brighten( imadjust(dum),.7);
x(:,:,i,1)=medfilt2(dum);
% cc2(:,:,i)= mat2gray(c2(:,:,i));
% cc3(:,:,i)= mat2gray(c3(:,:,i));
end
if exist('olap')
if ~isempty(olap)
if olap==0
tg=sum(sum(x,3),4);
i1=find(sum(tg,1)~=0);
i2=find(sum(tg,2)~=0);
lm2=[i1(1) i1(end)];
lm1=[i2(1) i2(end)] ;
% fg,imagesc(tg(lm1(1):lm1(2),lm2(1):lm2(2)))
x=x(lm1(1):lm1(2),lm2(1):lm2(2),:,:);
else
% round( size(x,2).*olap)
end
end
end
for i=1:size(x,4)
xm(:,:,i)=createMontageImage(permute(x(:,:,:,i),[1 2 4 3]));
% xm(:,:,i)=createMontageImage(permute(x(:,:,:,i),[ 3 2 4 1]));
end
ana=xm(:,:,1);
xm=xm(:,:,2:end) ;
h=figure('color','w');
imagesc( ana(:,:,[1 1 1]) );
% imagesc( xm(:,:,[1 1 1]) );
hold on;
% usespecificcolor
usemap=1
% tresh=.01
xv=xm.*nan;
for i=1:size(xm,3)
b2=xm(:,:,i);
t1 = b2 .* ( b2 >= tresh & b2 <= 1.0 ); % threshold second image
if usemap==0
t1(t1>0)=i;
end
xv(:,:,i)=t1;
end
ts =sum(xv,3);
talph=ts;
talph=ts>0;
talph=talph/2;
ih = imagesc( ts, 'tag','myIMAGE');colorbar;
colormap(actc)
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
try;
if isempty(col);
col=jet;
colmode=2;
end ;
end
if exist('col')==0
col={[0 0 1] [1 0 0] [0 1 0] [ 1 1 0] [0 1 1] [1 0 1]};
colmode=1;
end
if iscell(col)
eval(['col=[' num2str(col{1}) ']']);
colmode=2;
end
if colmode==1
n=size(xv,3)
% cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
cmap=cell2mat(col(1:n)');
try; cmap(end+1,:)=sum(cmap(1:2,:));end
try; cmap(end+1,:)=[0.7490 0 0.7490];end
if n==1; n2=1;end
if n==2; n2=3;end
if n==3; n2=6;end
cmap=cmap(1:n2,:);
if n==1; cmap=[cmap;cmap]; n2=2; end
colormap(cmap);
hb=colorbar;
caxis([1 n2]);
else
if size(col,1)~=1
colormap(col);
else
colormap(repmat(col,[32 1]));
end
hb=colorbar;
end
set(gca,'position',[0 0 1 1]);
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w');
function col=colorcheck(col)
cr={ 'b' [1 0 0]
'g' [0 .5 0]
'r' [1 0 0]
'c' [0 1 1]
'm' [1 0 1]
'y' [1 1 0]
'k' [0 0 0]
'w' [1 1 1] }
for i=1:size(cr,1)
ix= find(strcmp(col,cr{i,1}) );
if ~isempty(ix)
col{ ix} =cr{i,2}
end
end
% b blue . point - solid
% g green o circle : dotted
% r red x x-mark -. dashdot
% c cyan + plus -- dashed
% m magenta * star (none) no line
% y yellow s square
% k black d diamond
% w white v triangle (down)
% ^ triangle (up)
% < triangle (left)
% > triangle (right)
% p pentagram
% h hexagram
%
return
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
col={[0 0 1] [1 0 0] };
n=2
cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
colormap(cmap)
hb=colorbar
caxis([1 2])
set(gca,'position',[0 0 1 1])
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w')
% print('-djpeg','-r200','muell.jpg')
if 0
print('-djpeg','-r300','v2.jpg')
set( ih, 'AlphaData', talph/100 );
print('-djpeg','-r300','v1.jpg')
end
%%*****************************************
if 0
ls={
fullfile(pwd, 'v1.jpg')
fullfile(pwd, 'v2.jpg')
}
makegif('test3.gif',ls,.3);
end
% 00000000000000000000000000000000000000000000000000000000000
return
clear
h1=spm_vol('s.nii')
h2=spm_vol('c1.nii')
h3=spm_vol('c2.nii')
cc1=spm_read_vols(h1);
cc2=spm_read_vols(h2);
cc3=spm_read_vols(h3);
cc1=single(cc1);
cc2=single(cc2);
cc3=single(cc3);
slices=1:2:size(cc1,3)
cc1=cc1(:,:,slices);
cc2=cc2(:,:,slices);
cc3=cc3(:,:,slices);
%shiftDIM
cc1=flipdim(permute(cc1,[2 1 3]),1);
cc2=flipdim(permute(cc2,[2 1 3]),1);
cc3=flipdim(permute(cc3,[2 1 3]),1);
%% run2
for i=1:size(cc1,3)
dum= mat2gray(cc1(:,:,i));
dum=brighten( imadjust(dum),.7);
cc1(:,:,i)=medfilt2(dum);
% cc2(:,:,i)= mat2gray(c2(:,:,i));
% cc3(:,:,i)= mat2gray(c3(:,:,i));
end
% montage(permute(cc1,[1 2 4 3]))
a1=createMontageImage(permute(cc1,[1 2 4 3]));
b2=createMontageImage(permute(cc2,[1 2 4 3]));
b3=createMontageImage(permute(cc3,[1 2 4 3]));
fg
imagesc( a1(:,:,[1 1 1]) );
hold on;
% freezeColors
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
col={[0 0 1] [1 0 0] }
n=2
cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
colormap(cmap)
hb=colorbar
caxis([1 2])
set(gca,'position',[0 0 1 1])
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w')
% print('-djpeg','-r200','muell.jpg')
% print('-djpeg','-r200','v2.jpg')
%%*****************************************
return
h1=spm_vol('s.nii')
h2=spm_vol('c1.nii')
h3=spm_vol('c2.nii')
c1=spm_read_vols(h1);
c2=spm_read_vols(h2);
c3=spm_read_vols(h3);
alpha=.2
out2=nan.*c1;;
fg
for i=8%:size(c1,3)
b1=c1(:,:,10+i);
b2=c2(:,:,10+i);
b3=c3(:,:,10+i);
% out =dum(b1,b2,b2,.5, alpha);
% % subplot(4,3,i);
% image(out);
% axis('image');
% out2(:,:,i)=out;
end
%
% figure;
% imshow( first(:,:,[1 1 1]) ); % make the first a grey-scale image with three channels so it will not be affected by the colormap later on
% hold on;
% t_second = second .* ( second >= .6 & second <= 1.0 ); % threshold second image
% ih = imshow( t_second );
% set( ih, 'AlphaData', t_second );
% colormap jet
%% run
% b1=flipud(b1);
figure;
% b11=mat2gray(b1);
b11=brighten( imadjust(mat2gray(b1)),.7);
b11 = medfilt2(b11);
imagesc( b11(:,:,[1 1 1]) );
% imagesc( b1(:,:,[1 1 1]) ); % make the first a grey-scale image with three channels so it will not be affected by the colormap later on
% imagesc(b1);colormap gray
hold on;
% freezeColors
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
% talph(:,1:2:end)=0;
set( ih, 'AlphaData', talph );
colormap jet
'a'
|
github
|
philippboehmsturm/antx-master
|
p_displaySlices.m
|
.m
|
antx-master/mritools/various/p_displaySlices.m
| 38,526 |
utf_8
|
679a532e7f115eb7f7029b96ea39730a
|
function p_displaySlices(x)%(imgs, dispf)
% if isempty(x.cmap)
%
% eval(['x.cmap=' x.cmap ';']);
% if ~isnumeric(x.cmap)
% error('x.cmap: false colormap ') ;
% end
%
% end
if 0
%OVERLAY PARAMETER
x.views =0 ; %multiple view: [1] x.orient only [2] 2views fixed with 'sagittal' and 'axial' views
x.slices =[-30:15:30]; %slices to display
x.orient ='sagittal' ;%'axial','coronal','sagittal'
x.cmap =[];%colormap; [] if empty use defaults colormap otherwise use x.cmap=jet,or cmap=copper etc
x.crange =[]; %colorRange : [] if empty use subject's colorRange, otherwise 2numbers, e.g. [0 1000]
x.itype0 ={ 'Structural' 'Truecolour' } ;%colorSystem %'Structural' 'Truecolour' 'Negative blobs' 'Blobs'
x.intensity =[.5 .5];
end
if x.views==1
p_displaySlices2(x);
set(gcf,'color','k');
else
x.orient ='sagittal';
p_displaySlices2(x);
fig=findobj(0,'Tag','Graphics');
ax=sort(findobj(fig,'type','axes'));
set(ax,'units','normalized');
set(fig,'units','normalized');
try; delete(findobj(0,'tag','fig2'));end
fig2=figure(1000);set(fig2,'color','k','tag','fig2');
mxpos=[];
for u=1:length(ax)
ax2= copyobj(ax(u),fig2);
pos=get(ax2,'position');
pos(1)=pos(1)/2;
pos(3)=pos(3)/2;
set(ax2,'position',pos);
mxpos(u)=[pos(1)+pos(3)];
end
x.orient='axial';
p_displaySlices2(x);
fig=findobj(0,'Tag','Graphics');
ax=sort(findobj(fig,'type','axes'));
set(ax,'units','normalized');
set(fig,'units','normalized');
% fig2=figure(1000);set(fig2,'color',get(fig,'color'))
for u=1:length(ax)
ax2= copyobj(ax(u),fig2);
pos=get(ax2,'position');
pos(1)=pos(1)/2+max(mxpos);
pos(3)=pos(3)/2;
set(ax2,'position',pos);
end
hlb =findobj(fig,'tag','editbox');
set(0,'currentfigure',fig2);
axn=axes('position',[0 0 1 1]);
te=text( 0.05,.95, get(hlb,'string'),'fontsize',8,'color','w'); axis off;
% figure(fig2)
close(fig);
end
set(gcf,'InvertHardcopy','off');
function p_displaySlices2(x)
%STRUCT FOR OVERLAY
itype0 = x.itype0 ; % ={ 'Structural' 'Truecolour' } ;...%'Structural' 'Truecolour' 'Negative blobs' 'Blobs'
cmap = x.cmap ; % =[];%cm.actc;
orient = x.orient ; % ='sagittal' ;%'axial','coronal','sagittal'
crange = x.crange ; % =[]; %[0 1000]
slices = x.slices ; % =[-30:15:30];
intensity= x.intensity; % =[.7 .3];
subjectname=x.subjectname;%='XXXXX';
imgs =x.imgs;%={...
%'X:\ataxie\nifti\KIMSCA_K02\mpr\sKIMSCA_K_2-0003-00001-000176-01.nii,1'
%'X:\ataxie\nifti\KIMSCA_K02\epi\fKIMSCA_K_2-0008-00001-000001-01.nii,1'
%};
if 0
%STRUCT FOR OVERLAY
x.itype0 ={ 'Structural' 'Truecolour' } ;...%'Structural' 'Truecolour' 'Negative blobs' 'Blobs'
x.cmap =[];%cm.actc;
x.orient ='sagittal' ;%'axial','coronal','sagittal'
x.crange =[]; %[0 1000]
x.slices =[-30:15:30];
x.intensity =[.7 .3];
x.subjectname='XXXXX';
x.imgs={...
'X:\ataxie\nifti\KIMSCA_K02\mpr\sKIMSCA_K_2-0003-00001-000176-01.nii,1'
'X:\ataxie\nifti\KIMSCA_K02\epi\fKIMSCA_K_2-0008-00001-000001-01.nii,1'
};
end
% ########################################################################
dispf = 1;
warning off;
clear global SO
global SO
spm_input('!SetNextPos', 1);
% load images
nimgs = size(imgs);
% process names
nchars = 20;
imgns = spm_str_manip(imgs, ['rck' num2str(nchars)]);
% identify image types
cscale = [];
deftype = 1;
SO.cbar = [];
for i = 1:nimgs
SO.img(i).vol = spm_vol(imgs{i});
options = {'Structural','Truecolour', ...
'Blobs','Negative blobs'};
% if there are SPM results in the workspace, add this option
% if evalin('base','exist(''SPM'', ''var'')')
% options = {'Structural with SPM blobs', options{:}};
% end
itype=itype0(i);
% itype = spm_input(sprintf('Img %d: %s - image type?', i, imgns{i}), '+1', ...
% 'm', char(options),options, deftype);
imgns(i) = {sprintf('Img %d (%s)',i,itype{1})};
[mx mn] = slice_overlay('volmaxmin', SO.img(i).vol);
if ~isempty(strmatch('Structural', itype))
figure;
SO.img(i).cmap = gray;
close(gcf) ;
SO.img(i).range = [mn mx];
deftype = 2;
cscale = [cscale i];
if strcmp(itype,'Structural with SPM blobs')
slice_overlay('addspm',[],0);
end
else
SO.cbar = [SO.cbar i];
cprompt = ['Colormap: ' imgns{i}];
switch itype{1}
case 'Truecolour'
dcmap = 'actc';
drange = [mn mx];
cscale = [cscale i];
case 'Blobs'
dcmap = 'hot';
drange = [0 mx];
SO.img(i).prop = Inf;
case 'Negative blobs'
dcmap = 'winter';
drange = [0 mn];
SO.img(i).prop = Inf;
end
% SO.img(i).cmap = return_cmap(cprompt, dcmap);
% cm= load('actc.mat')
% cmap=cm.actc;
if isempty(cmap)
cmap=defaultcmap;
end
SO.img(i).cmap=cmap;
% try
% load(dcmap)
% SO.img(i).range = spm_input('Img val range for colormap','+1', 'e', drange, 2);
if isempty(crange)
SO.img(i).range=drange(:);
else
SO.img(i).range=crange(:);
end
end
end
ncmaps=length(cscale);
if ncmaps == 1
SO.img(cscale).prop = 1;
else
remcol=1;
for i = 1:ncmaps
ino = cscale(i);
% SO.img(ino).prop = spm_input(sprintf('%s intensity',imgns{ino}),...
% '+1', 'e', ...
% remcol/(ncmaps-i+1),1);
if isempty(intensity)
SO.img(ino).prop=remcol/(ncmaps-i+1);
else
SO.img(ino).prop=intensity(i);
end
remcol = remcol - SO.img(ino).prop;
end
end
% SO.transform = deblank(spm_input('Image orientation', '+1', ['Axial|' ...
% ' Coronal|Sagittal'], strvcat('axial','coronal','sagittal'), ...
% 1));
SO.transform=orient;%'axial';
% SO.transform='axial'
% use SPM figure window
SO.figure = spm_figure('GetWin', 'Graphics');
% slices for display
slice_overlay('checkso');
% SO.slices = spm_input('Slices to display (mm)', '+1', 'e', ...
% sprintf('%0.0f:%0.0f:%0.0f',...
% SO.slices(1),...
% mean(diff(SO.slices)),...
% SO.slices(end))...
% );
% SO.slices=[ -108 -88 -68 -48 -28 -8 12 32 ]
if isempty(slices)
SO.slices=SO.slices(1):20:SO.slices(end)
else %if length(slice)>1
SO.slices=slices(:)';
end
% and do the display
if dispf
slice_overlay
end
unit=get(gcf,'units');
set(gcf,'units','normalized');
h2 = uicontrol('Style', 'edit', 'String', char([{subjectname};x.imgs]),...
'units','normalized','Position', [.0 .92 .94 .07],'tag','editbox', ...
'backgroundcolor','w','horizontalalignment','center','fontsize',10,'fontweight','bold');
set(gcf,'units',unit);
set(h2,'max',3);
% set(h2,'Enable','off');
return
% function cmap = return_cmap(prompt,defmapn)
% cmap = [];
% while isempty(cmap)
% cmap = slice_overlay('getcmap', spm_input(prompt,'+1','s', defmapn));
% % cmap=jet
% end
% return
function cmap=defaultcmap
cmap=[...
0 0 0.0157
0 0 0.0353
0 0 0.0510
0 0 0.0706
0 0 0.0863
0 0 0.1059
0 0 0.1216
0 0 0.1412
0 0 0.1569
0 0 0.1765
0 0 0.1922
0 0 0.2118
0 0 0.2275
0 0 0.2471
0 0 0.2667
0 0 0.2824
0 0 0.3020
0 0 0.3176
0 0 0.3373
0 0 0.3529
0 0 0.3725
0 0 0.3882
0 0 0.4078
0 0 0.4235
0 0 0.4431
0 0 0.4588
0 0 0.4784
0 0 0.4941
0 0 0.5137
0 0 0.5333
0 0 0.5333
0 0.0196 0.5098
0 0.0431 0.4902
0 0.0667 0.4706
0 0.0863 0.4510
0 0.1098 0.4314
0 0.1333 0.4118
0 0.1529 0.3922
0 0.1765 0.3725
0 0.2000 0.3529
0 0.2196 0.3333
0 0.2431 0.3137
0 0.2667 0.2941
0 0.2863 0.2745
0 0.3098 0.2549
0 0.3333 0.2353
0 0.3529 0.2157
0 0.3765 0.1961
0 0.3961 0.1765
0 0.4196 0.1569
0 0.4431 0.1373
0 0.4627 0.1176
0 0.4863 0.0980
0 0.5098 0.0784
0 0.5294 0.0588
0 0.5529 0.0392
0 0.5765 0.0196
0 0.6000 0
0 0.6000 0
0.0706 0.6275 0
0.1412 0.6549 0
0.2118 0.6824 0
0.2824 0.7137 0
0.3529 0.7412 0
0.4235 0.7686 0
0.4941 0.8000 0
0.5647 0.8275 0
0.6353 0.8549 0
0.7059 0.8824 0
0.7765 0.9137 0
0.8471 0.9412 0
0.9176 0.9686 0
0.9882 1.0000 0
1.0000 1.0000 0
1.0000 0.9765 0
1.0000 0.9569 0
1.0000 0.9333 0
1.0000 0.9137 0
1.0000 0.8902 0
1.0000 0.8706 0
1.0000 0.8510 0
1.0000 0.8275 0
1.0000 0.8078 0
1.0000 0.7843 0
1.0000 0.7647 0
1.0000 0.7412 0
1.0000 0.7216 0
1.0000 0.7020 0
1.0000 0.6784 0
1.0000 0.6588 0
1.0000 0.6353 0
1.0000 0.6157 0
1.0000 0.5922 0
1.0000 0.5725 0
1.0000 0.5529 0
1.0000 0.5294 0
1.0000 0.5098 0
1.0000 0.4863 0
1.0000 0.4667 0
1.0000 0.4431 0
1.0000 0.4235 0
1.0000 0.4039 0
1.0000 0.3804 0
1.0000 0.3608 0
1.0000 0.3373 0
1.0000 0.3176 0
1.0000 0.2941 0
1.0000 0.2745 0
1.0000 0.2549 0
1.0000 0.2314 0
1.0000 0.2118 0
1.0000 0.1882 0
1.0000 0.1686 0
1.0000 0.1451 0
1.0000 0.1255 0
1.0000 0.1059 0
1.0000 0.0824 0
1.0000 0.0627 0
1.0000 0.0392 0
1.0000 0.0196 0
1.0000 0 0
];
function varargout = slice_overlay(action, varargin);
% Function to display + manage slice display
% Slice display works on a global structure SO
% with fields
% - img - array of images to display
% - img structs contain fields
% vol - vol struct info (see spm_vol)
% can also be vol containing image as 3d matrix
% set with slice_overlay('AddBlobs'...) call
% cmap - colormap for this image
% nancol - color for NaN. If scalar, this is an index into
% the image cmap. If 1x3 vector, it's a colour
% prop - proportion of intensity for this cmap/img
% if = Inf, gives split cmap effect where values of
% this cmap override previous image cmap values
% func - function to apply to image before scaling to cmap
% (and therefore before min/max thresholding. E.g. a func of
% 'i1(i1==0)=NaN' would convert zeros to NaNs
% range - 2x1 vector of values for image to distribute colormap across
% the first row of the colormap applies to the first
% value in 'range', and the last value to the second
% value in 'range'
% outofrange - behavior for image values to the left and
% right of image limits in 'range'. Left means
% colormap values < 1, i.e for image values <
% range(1), if (range(1)<range(2)), and image values >
% range(1) where (range(1)>range(2)). If missing,
% display min (for Left) and max (for Right) value from colormap.
% Otherwise should be a 2 element cell array, where
% the first element is the colour value for image values
% left of 'range', and the second is for image values
% right of 'range'. Scalar values for
% colour index the colormap, 3x1 vectors are colour
% values. An empty array attracts default settings
% appropriate to the mode - i.e. transparent colour (where
% SO.prop ~= Inf), or split colour. Empty cells
% default to 0. 0 specifies that voxels with this
% colour do not influence the image (split =
% background, true = black)
% hold - resampling order for image (see spm_sample_vol) -
% default 1
% background - value when resampling outside image - default
% NaN
%
% - transform - either - 4x4 transformation to apply to image slice position,
% relative to mm given by slicedef, before display
% or - text string, one of axial, coronal, sagittal
% These orientations assume the image is currently
% (after its mat file has been applied) axially
% oriented
% - slicedef - 2x3 array specifying dimensions for slice images in mm
% where rows are x,and y of slice image, and cols are neg max dim,
% slice separation and pos max dim
% - slices - vector of slice positions in mm in z (of transformed image)
% - figure - figure handle for slice display figure
% - refreshf - flag - if set or empty, refresh axis info for figure
% else assume this is OK
% - clf - flag, non zero -> clear figure before display. Redundant
% if refreshf == 0
% - area struct with fields
% position - bottom left, x size y size 1x4 vector of
% area in which to display slices
% units - one of
% inches,centimeters,normalized,points,{pixels}
% halign - one of left,{center},right
% valign - one of top,{middle},bottom
% - xslices - no of slices to display across figure (defaults to an optimum)
% - cbar - if empty, missing, no colourbar. If an array of integers, then
% indexes img array, and makes colourbar for each cmap for
% that img. Cbars specified in order of appearance L->R
% - labels - struct can be absent (-> default numerical labels)
% empty (SO.labels = []) (no labels) or contain fields
% colour - colour for label text
% size - font size in units normalized to slice axes
% format - if = cell array of strings =
% labels for each slice in Z. If is string, specifies
% sprintf format string for labelling in distance of the
% origin (Xmm=0, Ymm=0) of each slice from plane containing
% the AC, in mm, in the space of the transformed image
% - callback - callback string for button down on image panels. E.g.
% setting SO.callback to 'slice_overlay(''getpos'')' prints to
% the matlab window the equivalent position in mm of the
% position of a mouse click on one of the image slices
% - printstr - string for printing slice overlay figure window, e.g.
% 'print -dpsc -painters -noui' (the default)
% - printfile - name of file to print output to; default 'slices.ps'
%
% FORMAT slice_overlay
% Checks, fills SO struct (slice_overlay('checkso')), and
% displays slice overlay (slice_overlay('display'))
%
% FORMAT slice_overlay('checkso')
% Checks SO structure and sets defaults
%
% FORMAT cmap = slice_overlay('getcmap',cmapname)
% Gets colormap named in cmapname string
%
% FORMAT [mx mn] = slice_overlay('volmaxmin', vol)
% Returns maximum and minimum finite values from vol struct 'vol'
%
% FORMAT slice_overlay('addspm',SPM,dispf)
% Adds SPM blobs as new img to SO struct, split effect, 'hot' colormap,
% SPM structure is generated by calls to SPM results
% if not passed, it is fetched from the workspace
% If dispf is not passed, or nonzero, displays resulting SO figure also
%
% FORMAT slice_overlay('addblobs', imgno, XYZ, vals, mat)
% adds SPM blobs to img no 'imgno', as specified in
% XYZ - 3xN voxel coordinates of N blob values
% vals - N blob intensity values
% mat - 4x4 matrix specifying voxels -> mm
%
% FORMAT vol = slice_overlay('blobs2vol', XYZ, vals, mat)
% returns (pseudo) vol struct for 3d blob volume specified
% in matrices as above
%
% FORMAT slice_overlay('addmatrix', imgno, mat3d, mat)
% adds 3d matrix image vol to img imgno. Optionally
% mat - 4x4 matrix specifying voxels -> mm
%
% FORMAT vol = slice_overlay('matrix2vol', mat3d, mat)
% returns (pseudo) vol struct for 3d matrix
% input matrices as above
%
% FORMAT mmpos = slice_overlay('getpos')
% returns equivalent position in mm of last click on current axes (gca)
% if the axes contain an image slice (empty otherwise)
%
% FORMAT vals = slice_overlay('pointvals', XYZmm, holdlist)
% returns IxN matrix with values of each image 1..I, at each
% point 1..N specified in 3xN mm coordinate matrix XYZmm
% If specified, 'holdlist' contains I values giving hold
% values for resampling for each image (see spm_sample_vol)
%
% FORMAT slice_overlay('display')
% Displays slice overlay from SO struct
%
% FORMAT slice_overlay('print', filename, printstr)
% Prints slice overlay figure, usually to file. If filename is not
% passed/empty gets filename from SO.printfile. If printstr is not
% passed/empty gets printstr from SO.printstr
%
% V 0.8 2/8/00
% More or less beta - take care. Please report problems to
% Matthew Brett [email protected]
global SO
if nargin < 1
checkso;
action = 'display';
else
action = lower(action);
end
switch action
case 'checkso'
checkso;
case 'getcmap'
varargout = {getcmap(varargin{1})};
case 'volmaxmin'
[mx mn] = volmaxmin(varargin{1});
varargout = {mx, mn};
case 'addspm'
if nargin < 2
varargin{1} = [];
end
if nargin < 3
varargin{2} = 1;
end
if isempty(varargin{1})
% Fetch from workspace
errstr = sprintf(['Cannot find SPM variables in the workspace\n'...
'Please run SPM results GUI']);
V = spm('ver')
switch V(4:end)
case '99'
xSPM = evalin('base', 'SPM', ['error(' errstr ')']);
xSPM.M = evalin('base', 'VOL.M', ['error(' errstr ')']);
case '2'
xSPM = evalin('base', 'xSPM', ['error(' errstr ')']);
otherwise
error(['Strange SPM version ' V]);
end
else
xSPM = varargin{1};
end
newimg = length(SO.img)+1;
SO.img(newimg).vol = blobs2vol(xSPM.XYZ,xSPM.Z, xSPM.M);
SO.img(newimg).prop = Inf;
SO.img(newimg).cmap = hot;
SO.img(newimg).range = [0 max(xSPM.Z)];
SO.cbar = [SO.cbar newimg];
if varargin{2}
checkso;
slice_overlay('display');
end
case 'addblobs'
addblobs(varargin{1},varargin{2},varargin{3},varargin{4});
case 'blobs2vol'
varargout = {blobs2vol(varargin{1},varargin{2},varargin{3})};
case 'addmatrix'
if nargin<3,varargin{2}='';end
if nargin<4,varargin{3}='';end
addmatrix(varargin{1},varargin{2},varargin{3});
case 'matrix2vol'
if nargin<3,varargin{2}=[];end
varargout = {matrix2vol(varargin{1},varargin{2})};
case 'getpos'
varargout = {getpos};
case 'pointvals'
varargout = {pointvals(varargin{1})};
case 'print'
if nargin<2,varargin{1}='';end
if nargin<3,varargin{2}='';end
printfig(varargin{1}, varargin{2});
case 'display'
% get coordinates for plane
X=1;Y=2;Z=3;
dims = SO.slicedef;
xmm = dims(X,1):dims(X,2):dims(X,3);
ymm = dims(Y,1):dims(Y,2):dims(Y,3);
zmm = SO.slices;
[y x] = meshgrid(ymm,xmm');
vdims = [length(xmm),length(ymm),length(zmm)];
% no of slices, and panels (an extra for colorbars)
nslices = vdims(Z);
minnpanels = nslices;
cbars = 0;
if is_there(SO,'cbar')
cbars = length(SO.cbar);
minnpanels = minnpanels+cbars;
end
% get figure data
% if written to, the axes may be specified already
figno = figure(SO.figure);
% (re)initialize axes and stuff
% check if the figure is set up correctly
if ~SO.refreshf
axisd = flipud(findobj(SO.figure, 'Type','axes','Tag', 'slice overlay panel'));
npanels = length(axisd);
if npanels < vdims(Z)+cbars;
SO.refreshf = 1;
end
end
if SO.refreshf
% clear figure, axis store
if SO.clf, clf; end
axisd = [];
% prevent print inversion problems
set(figno,'InvertHardCopy','off');
% calculate area of display in pixels
parea = SO.area.position;
if ~strcmp(SO.area.units, 'pixels')
ubu = get(SO.figure, 'units');
set(SO.figure, 'units','pixels');
tmp = get(SO.figure, 'Position');
ascf = tmp(3:4);
if ~strcmp(SO.area.units, 'normalized')
set(SO.figure, 'units',SO.area.units);
tmp = get(SO.figure, 'Position');
ascf = ascf ./ tmp(3:4);
end
set(figno, 'Units', ubu);
parea = parea .* repmat(ascf, 1, 2);
end
asz = parea(3:4);
% by default, make most parsimonious fit to figure
yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2));
if ~is_there(SO, 'xslices')
% iteration needed to optimize, surprisingly. Thanks to Ian NS
axlen(X,:)=asz(1):-1:1;
axlen(Y,:)=yxratio*axlen(X,:);
panels = floor(asz'*ones(1,size(axlen,2))./axlen);
estnpanels = prod(panels);
tmp = find(estnpanels >= minnpanels);
if isempty(tmp)
error('Whoops, cannot fit panels onto figure');
end
b = tmp(1); % best fitting scaling
panels = panels(:,b);
axlen = axlen(:, b);
else
% if xslices is specified, assume X is flush with X figure dimensions
panels([X:Y],1) = [SO.xslices; 0];
axlen([X:Y],1) = [asz(X)/panels(X); 0];
end
% Axis dimensions are in pixels. This prevents aspect ratio rescaling
panels(Y) = ceil(minnpanels/panels(X));
axlen(Y) = axlen(X)*yxratio;
% centre (etc) panels in display area as required
divs = [Inf 2 1];the_ds = [0;0];
the_ds(X) = divs(strcmp(SO.area.halign, {'left','center','right'}));
the_ds(Y) = divs(strcmp(SO.area.valign, {'bottom','middle','top'}));
startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds;
% make axes for panels
r=0;c=1;
npanels = prod(panels);
lastempty = npanels-cbars;
for i = 1:npanels
% panel userdata
if i<=nslices
u.type = 'slice';
u.no = zmm(i);
elseif i > lastempty
u.type = 'cbar';
u.no = i - lastempty;
else
u.type = 'empty';
u.no = i - nslices;
end
axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen'];
axisd(i) = axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'YTick',[],...
'YTickLabel',[],...
'Box','on',...
'XLim',[1 vdims(X)],...
'YLim',[1 vdims(Y)],...
'Units', 'pixels',...
'Position',axpos,...
'Tag','slice overlay panel',...
'UserData',u);
r = r+1;
if r >= panels(X)
r = 0;
c = c+1;
end
end
end
% sort out labels
if is_there(SO,'labels')
labels = SO.labels;
if iscell(labels.format)
if length(labels.format)~=vdims(Z)
error(...
sprintf('Oh dear, expecting %d labels, but found %d',...
vdims(Z), length(labels.contents)));
end
else
% format string for mm from AC labelling
fstr = labels.format;
labels.format = cell(vdims(Z),1);
acpt = SO.transform * [0 0 0 1]';
for i = 1:vdims(Z)
labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))};
end
end
end
% modify colormaps with any new colours
nimgs = length(SO.img);
lrn = zeros(nimgs,3);
cmaps = cell(nimgs);
for i = 1:nimgs
cmaps(i)={SO.img(i).cmap};
lrnv = {SO.img(i).outofrange{:}, SO.img(i).nancol};
for j = 1:length(lrnv)
if prod(size(lrnv{j}))==1
lrn(i,j) = lrnv{j};
else
cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]};
lrn(i,j) = size(cmaps{i},1);
end
end
end
% cycle through slices displaying images
nvox = prod(vdims(1:2));
pandims = [vdims([2 1]) 3]; % NB XY transpose for display
zimg = zeros(pandims);
for i = 1:nslices
ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)];
img = zimg;
for j = 1:nimgs
thisimg = SO.img(j);
% to voxel space of image
vixyz = inv(SO.transform*thisimg.vol.mat)*ixyzmm;
% raw data
if is_there(thisimg.vol, 'imgdata')
V = thisimg.vol.imgdata;
else
V = thisimg.vol;
end
i1 = spm_sample_vol(V,vixyz(X,:),vixyz(Y,:),vixyz(Z,:), ...
[thisimg.hold thisimg.background]);
if is_there(thisimg, 'func')
eval(thisimg.func);
end
% transpose to reverse X and Y for figure
i1 = reshape(i1, vdims(1:2))';
% rescale to colormap
[csdata badvals]= scaletocmap(...
i1,...
thisimg.range(1),...
thisimg.range(2),...
cmaps{j},...
lrn(j,:));
% take indices from colormap to make true colour image
iimg = reshape(cmaps{j}(csdata(:),:),pandims);
tmp = repmat(logical(~badvals),[1 1 3]);
if thisimg.prop ~= Inf % truecolor overlay
img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop;
else % split colormap effect
img(tmp) = iimg(tmp);
end
end
% threshold out of range values
img(img>1) = 1;
image('Parent', axisd(i),...
'ButtonDownFcn', SO.callback,...
'CData',img);
if is_there(SO,'labels')
text('Parent',axisd(i),...
'Color', labels.colour,...
'FontUnits', 'normalized',...
'VerticalAlignment','bottom',...
'HorizontalAlignment','left',...
'Position', [1 1],...
'FontSize',labels.size,...
'ButtonDownFcn', SO.callback,...
'String', labels.format{i});
end
end
for i = (nslices+1):npanels
set(axisd(i),'Color',[0 0 0]);
end
% add colorbar(s)
for i = 1:cbars
axno = axisd(end-cbars+i);
cbari = SO.img(SO.cbar(i));
cml = size(cbari.cmap,1);
p = get(axno, 'Position');; % position of last axis
cw = p(3)*0.2;
ch = p(4)*0.75;
pc = p(3:4)/2;
[axlims idxs] = sort(cbari.range);
a=axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'Units', 'pixels',...
'YLim', axlims,...
'FontUnits', 'normalized',...
'FontSize', 0.075,...
'YColor',[1 1 1],...
'Tag', 'cbar',...
'Box', 'off',...
'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]...
);
ih = image('Parent', a,...
'YData', axlims(idxs),...
'CData', reshape(cbari.cmap,[cml,1,3]));
end
otherwise
error(sprintf('Unrecognized action string %s', action));
% end switch action
end
return
function checkso
% checks and fills SO structure
global SO
% figure
if is_there(SO, 'figure')
try
if ~strcmp(get(SO.figure,'Type'),'figure')
error('Figure handle is not a figure')
end
catch
error('Figure handle is not a valid figure')
end
else
% no figure handle. Try spm figure, then gcf
SO.figure = spm_figure('FindWin', 'Graphics');
if isempty(SO.figure)
SO.figure = gcf;
end
end
% set defaults for SPM figure
if strcmp(get(SO.figure, 'Tag'),'Graphics')
% position figure nicely for SPM
defstruct = struct('position', [0 0 1 0.92], 'units', 'normalized', ...
'valign', 'top');
SO = set_def(SO, 'area', defstruct);
SO.area = set_def(SO.area, 'position', defstruct.position);
SO.area = set_def(SO.area, 'units', defstruct.units);
SO.area = set_def(SO.area, 'valign', defstruct.valign);
end
SO = set_def(SO, 'clf', 1);
% orientation; string or 4x4 matrix
orientn = [];
SO = set_def(SO, 'transform', 'axial');
if ischar(SO.transform)
orientn = find(strcmpi(SO.transform, {'axial','coronal','sagittal'}));
if isempty(orientn)
error(sprintf('Unexpected orientation %s', SO.transform));
end
ts = [0 0 0 0 0 0 1 1 1;...
0 0 0 pi/2 0 0 1 -1 1;...
0 0 0 pi/2 0 -pi/2 -1 1 1];
SO.transform = spm_matrix(ts(orientn,:));
end
% default slice size, slice matrix depends on orientation
if ~is_there(SO,'slicedef' | ~is_there(SO, 'slices'))
% take image sizes from first image
V = SO.img(1).vol;
D = V.dim(1:3);
T = SO.transform * V.mat;
vcorners = [1 1 1; D(1) 1 1; 1 D(2) 1; D(1:2) 1; ...
1 1 D(3); D(1) 1 D(3); 1 D(2:3) ; D(1:3)]';
corners = T * [vcorners; ones(1,8)];
SC = sort(corners');
vxsz = sqrt(sum(T(1:3,1:3).^2));
SO = set_def(SO, 'slicedef',...
[SC(1,1) vxsz(1) SC(8,1);SC(1,2) vxsz(2) SC(8,2)]);
SO = set_def(SO, 'slices',[SC(1,3):vxsz(3):SC(8,3)]);
end
% no colourbars by default
SO = set_def(SO, 'cbars', []);
% always refresh figure window, by default
SO = set_def(SO, 'refreshf', 1);
% labels
defstruct = struct('colour',[1 1 1],'size',0.075,'format', '%+3.0f');
if ~isfield(SO, 'labels') % no field, -> default
SO.labels = defstruct;
elseif ~isempty(SO.labels) % empty -> no labels
% colour for slice labels
SO.labels = set_def(SO.labels, 'colour', defstruct.colour);
% font size normalized to image axis
SO.labels = set_def(SO.labels, 'size', defstruct.size);
% format string for slice labels
SO.labels = set_def(SO.labels, 'format', defstruct.format);
end
% callback
SO = set_def(SO, 'callback', ';');
% figure area stuff
defarea = struct('position',[0 0 1 1],'units','normalized');
SO = set_def(SO, 'area', defarea);
if ~is_there(SO.area, 'position')
SO.area = defarea;
end
if ~is_there(SO.area,'units')
if (all(SO.area.position>=0 & SO.area.position<=1))
SO.area.units = 'normalized';
else
SO.area.units = 'pixels';
end
end
SO.area = set_def(SO.area,'halign', 'center');
SO.area = set_def(SO.area,'valign', 'middle');
% printing
SO = set_def(SO, 'printstr', 'print -dpsc -painters -noui');
SO = set_def(SO, 'printfile', 'slices.ps');
% fill various img arguments
% would be nice to use set_def, but we can't
% set colour intensities as we go
remcol = 1;
for i = 1:length(SO.img)
if ~is_there(SO.img(i),'hold')
if ~is_there(SO.img(i).vol,'imgdata')
% normal file vol struct
SO.img(i).hold = 1;
else
% 3d matrix vol struct
SO.img(i).hold = 0;
end
end
if ~is_there(SO.img(i),'background')
SO.img(i).background = NaN;
end
if ~is_there(SO.img(i),'prop')
% default is true colour
SO.img(i).prop = remcol/(length(SO.img)-i+1);
remcol = remcol - SO.img(i).prop;
end
if ~is_there(SO.img(i),'range')
[mx mn] = volmaxmin(SO.img(i).vol);
SO.img(i).range = [mn mx];
end
if ~is_there(SO.img(i),'cmap')
if SO.img(i).prop == Inf; % split map
if SO.range(1)<SO.range(2)
SO.img(i).cmap = getcmap('hot');
else
SO.img(i).cmap = getcmap('winter');
end
else % true colour
SO.img(i).cmap = getcmap('actc');
end
end
if ~is_there(SO.img(i),'outofrange')
% this can be complex, and depends on split/true colour
if SO.img(i).prop == Inf % split colour
if xor(SO.img(i).range(1) < SO.img(i).range(2), ...
SO.img(i).range(2) < 0)
SO.img(i).outofrange = {[0],size(SO.img(i).cmap,1)};
else
SO.img(imgno).outofrange={[1], [0]};
end
else % true colour
SO.img(i).outofrange = {1,size(SO.img(i).cmap,1)};
end
end
for j=1:2
if isempty(SO.img(i).outofrange{j})
SO.img(i).outofrange(j) = {0};
end
end
if ~is_there(SO.img(i),'nancol')
SO.img(i).nancol = 0;
end
end
return
function tf = is_there(a, fname)
% returns true if field fname is present in struct a, and not empty
tf = isfield(a, fname);
if tf
tf = ~isempty(getfield(a, fname));
end
return
function [img, badvals]=scaletocmap(inpimg,mn,mx,cmap,lrn)
img = (inpimg-mn)/(mx-mn); % img normalized to mn=0,mx=1
cml = size(cmap,1);
if cml==1 % values between 0 and 1 -> 1
img(img>=0 & img<=1)=1;
else
img = img*(cml-1)+1;
end
outvals = {img<1, img>cml, isnan(img)};
img= round(img);
badvals = zeros(size(img));
for i = 1:length(lrn)
if lrn(i)
img(outvals{i}) = lrn(i);
else
badvals = badvals | outvals{i};
img(outvals{i}) = 1;
end
end
return
function st = set_def(st, fld, def)
if ~is_there(st, fld)
st = setfield(st, fld, def);
end
return
function addblobs(imgno, xyz,vals,mat)
global SO
if isempty(imgno)
imgno = length(SO.img);
end
if ~isempty(xyz)
SO.img(imgno).vol = blobs2vol(xyz,vals,mat);
end
function vol = blobs2vol(xyz,vals,mat)
vol = [];
if ~isempty(xyz),
rcp = round(xyz);
vol.dim = max(rcp,[],2)';
off = rcp(1,:) + vol.dim(1)*(rcp(2,:)-1+vol.dim(2)*(rcp(3,:)-1));
vol.imgdata = zeros(vol.dim)+NaN;
vol.imgdata(off) = vals;
vol.imgdata = reshape(vol.imgdata,vol.dim);
vol.mat = mat;
end
return
function addmatrix(imgno,mat3d,mat)
global SO
if isempty(imgno)
imgno = length(SO.img);
end
if nargin<3
mat = [];
end
if ~isempty(mat3d)
SO.img(imgno).vol = matrix2vol(mat3d,mat);
end
function vol = matrix2vol(mat3d,mat)
if nargin < 2
mat = spm_matrix([]);
end
if isempty(mat)
mat = spm_matrix([]);
end
vol = [];
if ~isempty(mat3d)
vol.imgdata = mat3d;
vol.mat = mat;
vol.dim = size(mat3d);
end
return
function [mx,mn] = volmaxmin(vol)
if is_there(vol, 'imgdata')
try
tmp = vol.imgdata(finite(vol.imgdata));
catch
tmp = vol.imgdata(isfinite(vol.imgdata));
end
mx = max(tmp);
mn = min(tmp);
else
mx = -Inf;mn=Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),[0 NaN]);
try
tmp = tmp(find(finite(tmp(:))));
catch
tmp = tmp(find(isfinite(tmp(:))));
end
if ~isempty(tmp)
mx = max([mx; tmp]);
mn = min([mn; tmp]);
end
end
end
return
function cmap = getcmap(acmapname)
% get colormap of name acmapname
if ~isempty(acmapname)
cmap = evalin('base',acmapname,'[]');
if isempty(cmap) % not a matrix, is it...
% a colour name?
tmp = strcmp(acmapname, {'red','green','blue'});
if any(tmp)
cmap = zeros(64,3);
cmap(:,tmp) = ((0:63)/63)';
else
% a .mat file?
[p f e] = fileparts(acmapname);
acmat = fullfile(p, [f '.mat']);
if exist(acmat, 'file')
s = struct2cell(load(acmat));
cmap = s{1};
end
end
end
end
if size(cmap, 2)~=3
warning('Colormap was not an N by 3 matrix')
cmap = [];
end
return
function mmpos = getpos
% returns point location from last click, in mm
global SO
mmpos=[];
pos = get(gca, 'CurrentPoint');
u = get(gca, 'UserData');
if is_there(u, 'type')
if strcmp(u.type, 'slice') % is slice panel
mmpos = (pos(1,1:2)'-1).*SO.slicedef(:,2)+SO.slicedef(:,1);
mmpos = inv(SO.transform) * [mmpos; u.no; 1];
mmpos = mmpos(1:3,1);
end
end
return
function vals = pointvals(XYZmm, holdlist)
% returns values from all the images at points given in XYZmm
global SO
if nargin < 2
holdlist = [SO.img(:).hold];
end
X=1;Y=2;Z=3;
nimgs = length(SO.img);
nvals = size(XYZmm,2);
vals = zeros(nimgs,nvals)+NaN;
if size(XYZmm,1)~=4
XYZmm = [XYZmm(X:Z,:); ones(1,nvals)];
end
for i = 1:nimgs
I = SO.img(i);
XYZ = I.vol.mat\XYZmm;
if ~is_there(I.vol, 'imgdata')
vol = I.vol;
else
vol = I.vol.imgdata;
end
vals(i,:) = spm_sample_vol(vol, XYZ(X,:), XYZ(Y,:),XYZ(Z,:),[holdlist(i) ...
I.background]);
end
return
function printfig(filename,printstr)
% print slice overlay figure
% based on spm_figure print, and including fix from thence for ps printing
global SO;
if nargin < 1
filename = [];
end
if isempty(filename)
filename = SO.printfile;
end
if nargin < 2
printstr = '';
end
if isempty(printstr)
printstr = SO.printstr;
end
%-Note current figure, & switch to figure to print
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',SO.figure)
%-Temporarily change all units to normalized prior to printing
% (Fixes bizarre problem with stuff jumping around!)
%-----------------------------------------------------------------------
H = findobj(get(SO.figure,'Children'),'flat','Type','axes');
un = cellstr(get(H,'Units'));
set(H,'Units','normalized')
%-Print
%-----------------------------------------------------------------------
err = 0;
try, eval([printstr ' ' filename]), catch, err=1; end
if err
errstr = lasterr;
tmp = [find(abs(errstr)==10),length(errstr)+1];
str = {errstr(1:tmp(1)-1)};
for i = 1:length(tmp)-1
if tmp(i)+1 < tmp(i+1)
str = [str, {errstr(tmp(i)+1:tmp(i+1)-1)}];
end
end
str = {str{:}, '','- print command is:',[' ',printstr ' ' filename],...
'','- current directory is:',[' ',pwd],...
'',' * nothing has been printed *'};
for i=1:length(str)
disp(str{i});end
end
set(H,{'Units'},un)
set(0,'CurrentFigure',cF)
return
|
github
|
philippboehmsturm/antx-master
|
simpleoverlay3.m
|
.m
|
antx-master/mritools/various/simpleoverlay3.m
| 12,447 |
utf_8
|
cbc8c0bf8f51253220a677faf2b685ef
|
function h=simpleoverlay3(ls,flipdims , slices, tresh, col, olap,txt)
% f1='V:\harmsSC\s_neu_s20150505SM01_1_x_x_1\c1fT2.nii'
% f2 ='V:\harmsSC\s_neu_s20150505SM01_1_x_x_1\fT2.nii'
% simpleoverlay3({f2,f1},[1 3 2],'3',.01,{'r'},'%40');
% simpleoverlay3({f2,f1},[1 -3 -2],'3',.01,{'summer'},'%40');
% simpleoverlay3({f2,f1},[1 -3 -2],'3',.01,{'r'},'%40');
% FINAL: for SPMmouse-directions
% simpleoverlay3({f2,f1},[3 -1 2],'2',.1,{'r'},'%40'); %
% simpleoverlay3({f2,f1},[3 -1 2],[],.01,{'r'},'%40');
% simpleoverlay3({f2,f1},[3 -1 2],[],.01,{'flipud(autumn)'},'%40');
% simpleoverlay3({f2,f1},[3 -1 2],[],.01,{'(autumn)'},'%40');
%RGB-colors
% ls={t2file;fullfile(t2path,'c1fT2.nii');fullfile(t2path,'c3fT2.nii') }
% simpleoverlay3(ls,[3 -1 2],[],.01,{'r','b','g'},'%40');
% ls={t2file;fullfile(t2path,'c1fT2.nii');fullfile(t2path,'c3fT2.nii') }
% simpleoverlay3(ls,[3 -1 2],[],.01,{'jet'},'%40');
% simpleoverlay3(ls,[3 -1 2],['4'],.01,{'r','b'},'%40');
if 0
ls3={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
'c2s20150908_FK_C1M04_1_3_1.nii'
'c3s20150908_FK_C1M04_1_3_1.nii'
}
ls2={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
'c2s20150908_FK_C1M04_1_3_1.nii'
}
ls1={
's20150908_FK_C1M04_1_3_1.nii'
'c1s20150908_FK_C1M04_1_3_1.nii'
}
slices=1:32
tresh=.01
end
% if exist('col')
% col=colorcheck(col)
% end
% %% ==============================
% if isempty(slices)
h1=spm_vol(ls{1});
% slices=1:h1.dim(3);
% end
for i=1:length(ls)
h1=spm_vol(ls{i});
if i==1
href=h1;
dum=single(spm_read_vols(h1));
else
% 'a'
inhdr = spm_vol(ls{i}); %load header
inimg = spm_read_vols(inhdr); %load volume
tarhdr = href;%spm_vol(ls{2}); %load header
[outhdr,outimg] = nii_reslice_target(inhdr,inimg, tarhdr); %resize in memory
dum=outimg;
end
% dum=dum(:,:,slices);
dum=dum./max(dum(:));
% dum=flipdim(permute(dum,[2 1 3]),1);
% if dirs==1
% dum=permute(dum,[1 3 2 ]);
% elseif dirs==2
% dum=permute(dum,[2 1 3 ]);
% elseif dirs==3
% dum=permute(dum,[3 2 1 ]);
% end
if i==1
x=single(zeros([size(dum) size(ls,1) ])) ;
end
x(:,:,:,i)=dum;
end
if exist('flipdims') || ~isempty(flipdims)
flips=sign(flipdims);
perms=abs(flipdims);
isflip=find(flips==-1);
for i=1:length(isflip)
x=flipdim(x,isflip(i));
end
%permute
x=permute(x,[perms 4]);
end
disp(['size(x): ' num2str(size(x))]);
%======slice =================
if isempty(slices)
slices=1:size(x,3);
end
if ischar(slices) %'2' or '5'-->use every 2nd,5th slice
slicespace=str2num(slices);
slices=1:slicespace:size(x,3);
end
x=x(:,:,slices,:);
for i=1:size(x,3)
dum= mat2gray(x(:,:,i,1));
dum=brighten( imadjust(dum),.7);
x(:,:,i,1)=medfilt2(dum);
% cc2(:,:,i)= mat2gray(c2(:,:,i));
% cc3(:,:,i)= mat2gray(c3(:,:,i));
end
% olap='%20'
if exist('olap')
%%backgroundNoise
if ~isempty(olap)
if isnumeric(olap)
if olap==0
tg=sum(sum(x,3),4);
i1=find(sum(tg,1)~=0);
i2=find(sum(tg,2)~=0);
lm2=[i1(1) i1(end)];
lm1=[i2(1) i2(end)] ;
% fg,imagesc(tg(lm1(1):lm1(2),lm2(1):lm2(2)))
x=x(lm1(1):lm1(2),lm2(1):lm2(2),:,:);
end
elseif ischar(olap)
%%cut percentual
olappercent=str2num(olap(2:end));
sixx=size(x);
npixLR=round(sixx(1:2)*(olappercent/2)/100) ;
x=x(npixLR(1):sixx(1)-npixLR(1)+1 ,npixLR(2):sixx(2)-npixLR(2)+1,:,:);
disp(['size(x): ' num2str(size(x))]);
end
end
end
xm=[];
for i=1:size(x,4)
xm(:,:,i)=createMontageImage(permute(x(:,:,:,i),[1 2 4 3]));
% xm(:,:,i)=createMontageImage(permute(x(:,:,:,i),[ 3 2 4 1]));
end
ana=xm(:,:,1);
xm=xm(:,:,2:end) ;
h=figure('color','w');
imagesc( ana(:,:,[1 1 1]) );
% imagesc( xm(:,:,[1 1 1]) );
hold on;
% usespecificcolor
if ischar(col{1}) && length(col{1})==1 ;%length(col)>1
usemap=0 ; %addonCOLOR
modus=3;
else
usemap=1; %colormap
modus=1;
end
% tresh=.01
xv=xm.*nan;
for i=1:size(xm,3)
b2=xm(:,:,i);
t1 = b2 .* ( b2 >= tresh & b2 <= 1.0 ); % threshold second image
if usemap==0
t1(t1>0)=i;
end
xv(:,:,i)=t1;
end
ts =sum(xv,3);
talph=ts;
talph=ts>0;
talph=talph/2;
ih = imagesc( ts, 'tag','myIMAGE');colorbar;
cmap2=col{1};
if modus~=3;
try;
eval(['cmap3=' cmap2 ';']) ; colormap(cmap3);
modus=1;
catch
colormap(actc);
modus=1;
end
end
hb=colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
if modus==2 %r,g,b colors
try;
if isempty(col);
col=jet;
colmode=2;
end ;
end
if exist('col')==0
col={[0 0 1] [1 0 0] [0 1 0] [ 1 1 0] [0 1 1] [1 0 1]};
colmode=1;
end
if iscell(col)
eval(['col=[' num2str(col{1}) '];']);
colmode=2;
end
if colmode==1
n=size(xv,3)
% cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
cmap=cell2mat(col(1:n)');
try; cmap(end+1,:)=sum(cmap(1:2,:));end
try; cmap(end+1,:)=[0.7490 0 0.7490];end
if n==1; n2=1;end
if n==2; n2=3;end
if n==3; n2=6;end
cmap=cmap(1:n2,:);
if n==1; cmap=[cmap;cmap]; n2=2; end
colormap(cmap);
hb=colorbar;
caxis([1 n2]);
else
if size(col,1)~=1
colormap(col);
else
colormap(repmat(col,[32 1]));
end
hb=colorbar;
end
end%modeis
set(gca,'position',[0 0 1 1]);
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w');
%% additive colors
if modus==3
colx=colorcheck(col) ;
n=size(xv,3)
cmap=cell2mat(colx(1:n)');
try; cmap(end+1,:)=sum(cmap(1:2,:))/2;end
try; cmap(end+1,:)=[0.7490 0 0.7490];end
if n==1; n2=1;end
if n==2; n2=3;end
if n==3; n2=6;end
cmap=cmap(1:n2,:);
if n==1; cmap=[cmap;cmap]; n2=2; end
colormap(cmap);
hb=colorbar;
caxis([1 n2]);
end
if exist('txt') && ~isempty(txt)
xl=xlim;
yl=ylim;
posperc=[.05 .95 ];%LR & UD
te=text( diff(xl)*posperc(1)+xl(1) , yl(2)-diff(yl)*posperc(2)+yl(1),txt);
set(te,'color','w','fontsize',10,'fontweight','bold','tag','text');
set(te,'interpreter','none');
nshift=1;
te=text( diff(xl)*posperc(1)+xl(1)+nshift , yl(2)-diff(yl)*posperc(2)+yl(1)+nshift,txt);
set(te,'color','r','fontsize',10,'fontweight','bold','tag','text');
set(te,'interpreter','none');
% delete(findobj(gca,'tag','text'))
end
function col=colorcheck(col)
cr={'b' [0 0 1]
'g' [0 .5 0]
'r' [1 0 0]
'c' [0 1 1]
'm' [1 0 1]
'y' [1 1 0]
'k' [0 0 0]
'w' [1 1 1] };
for i=1:size(cr,1)
ix= find(strcmp(col,cr{i,1}) );
if ~isempty(ix)
col{ ix} =cr{i,2};
end
end
% b blue . point - solid
% g green o circle : dotted
% r red x x-mark -. dashdot
% c cyan + plus -- dashed
% m magenta * star (none) no line
% y yellow s square
% k black d diamond
% w white v triangle (down)
% ^ triangle (up)
% < triangle (left)
% > triangle (right)
% p pentagram
% h hexagram
%
return
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
col={[0 0 1] [1 0 0] };
n=2
cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
colormap(cmap)
hb=colorbar
caxis([1 2])
set(gca,'position',[0 0 1 1])
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w')
% print('-djpeg','-r200','muell.jpg')
if 0
print('-djpeg','-r300','v2.jpg')
set( ih, 'AlphaData', talph/100 );
print('-djpeg','-r300','v1.jpg')
end
%%*****************************************
if 0
ls={
fullfile(pwd, 'v1.jpg')
fullfile(pwd, 'v2.jpg')
}
makegif('test3.gif',ls,.3);
end
% 00000000000000000000000000000000000000000000000000000000000
return
clear
h1=spm_vol('s.nii')
h2=spm_vol('c1.nii')
h3=spm_vol('c2.nii')
cc1=spm_read_vols(h1);
cc2=spm_read_vols(h2);
cc3=spm_read_vols(h3);
cc1=single(cc1);
cc2=single(cc2);
cc3=single(cc3);
slices=1:2:size(cc1,3)
cc1=cc1(:,:,slices);
cc2=cc2(:,:,slices);
cc3=cc3(:,:,slices);
%shiftDIM
cc1=flipdim(permute(cc1,[2 1 3]),1);
cc2=flipdim(permute(cc2,[2 1 3]),1);
cc3=flipdim(permute(cc3,[2 1 3]),1);
%% run2
for i=1:size(cc1,3)
dum= mat2gray(cc1(:,:,i));
dum=brighten( imadjust(dum),.7);
cc1(:,:,i)=medfilt2(dum);
% cc2(:,:,i)= mat2gray(c2(:,:,i));
% cc3(:,:,i)= mat2gray(c3(:,:,i));
end
% montage(permute(cc1,[1 2 4 3]))
a1=createMontageImage(permute(cc1,[1 2 4 3]));
b2=createMontageImage(permute(cc2,[1 2 4 3]));
b3=createMontageImage(permute(cc3,[1 2 4 3]));
fg
imagesc( a1(:,:,[1 1 1]) );
hold on;
% freezeColors
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
talph(talph==0)=nan;
set( ih, 'AlphaData', talph );
col={[0 0 1] [1 0 0] }
n=2
cmap=[ repmat(col{1},[32 1]); repmat(col{2},[32 1])]
colormap(cmap)
hb=colorbar
caxis([1 2])
set(gca,'position',[0 0 1 1])
set(hb,'position',[0.015 0.1 .01 .2],'xcolor','w','ycolor','w')
% print('-djpeg','-r200','muell.jpg')
% print('-djpeg','-r200','v2.jpg')
%%*****************************************
return
h1=spm_vol('s.nii')
h2=spm_vol('c1.nii')
h3=spm_vol('c2.nii')
c1=spm_read_vols(h1);
c2=spm_read_vols(h2);
c3=spm_read_vols(h3);
alpha=.2
out2=nan.*c1;;
fg
for i=8%:size(c1,3)
b1=c1(:,:,10+i);
b2=c2(:,:,10+i);
b3=c3(:,:,10+i);
% out =dum(b1,b2,b2,.5, alpha);
% % subplot(4,3,i);
% image(out);
% axis('image');
% out2(:,:,i)=out;
end
%
% figure;
% imshow( first(:,:,[1 1 1]) ); % make the first a grey-scale image with three channels so it will not be affected by the colormap later on
% hold on;
% t_second = second .* ( second >= .6 & second <= 1.0 ); % threshold second image
% ih = imshow( t_second );
% set( ih, 'AlphaData', t_second );
% colormap jet
%% run
% b1=flipud(b1);
figure;
% b11=mat2gray(b1);
b11=brighten( imadjust(mat2gray(b1)),.7);
b11 = medfilt2(b11);
imagesc( b11(:,:,[1 1 1]) );
% imagesc( b1(:,:,[1 1 1]) ); % make the first a grey-scale image with three channels so it will not be affected by the colormap later on
% imagesc(b1);colormap gray
hold on;
% freezeColors
t1 = b2 .* ( b2 >= .01 & b2 <= 1.0 ); % threshold second image
t2 = b3 .* ( b3 >= .01 & b3 <= 1.0 ); % threshold second image
t1(t1>0)=1;
t2(t2>0)=2;
ts =(t1+t2);
talph=ts>0;
talph=talph/2;
ih = imagesc( ts);colorbar;
% talph(:,1:2:end)=0;
set( ih, 'AlphaData', talph );
colormap jet
'a'
|
github
|
philippboehmsturm/antx-master
|
makebrainmask2.m
|
.m
|
antx-master/mritools/various/makebrainmask2.m
| 1,426 |
utf_8
|
3f37fd902c20f48218fa5ef12c1fa7e5
|
function makebrainmask2(tpm, thresh, outfilename)
%% make brain mask from TPM
% tpm: cellaray with 2 or 3 or x compartiments
% tpm= { 'wc1T2.nii' 'wc2T2.nii' 'wc3T2.nii'}'
% tpm= { 'wc1T2.nii' 'wc2T2.nii' }';
% tpm=fullpath(pwd,tpm);
% makebrainmask2(tpm, thresh, 'test1.nii')
% thresh=.2;
for i=1:length(tpm);
[h1 d1 ]=rgetnii(tpm{i});
if i==1
dm=d1.*0;
end
dm=dm+single((d1>=thresh));
end
dm=dm>.5;
%-------
%% fill holes (over 3d volume does not work accurately -->slieceWise)
df=dm;
for i=1:size(df,3)
df(:,:,i)= imfill(df(:,:,i),'holes') ;
end
%
df2=df.*0;
for i=1:size(df,3)
BW=df(:,:,i);
[B,L] = bwboundaries(BW,4,'noholes');
% [L,num] = bwlabel(BW,4)
num=cell2mat(cellfun(@(x) {size(x,1)} ,B));
delthresh=.25;
pnum=num.*100./(sum(num));
isurv=find(pnum>(delthresh*100));
L2=L.*0;
for k=1:length(isurv)
L2( L==isurv(k) )=1;
end
df2(:,:,i)=L2;
% fg(14);cla
% imagesc(label2rgb(L, @jet, [.5 .5 .5]));
% hold on
% for k = 1:length(isurv)
% boundary = B{isurv(k)};
% plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)
% end
% title(i);
% drawnow
% pause
end
df2=df;
%----------
h2=h1;
h2.dt=[2 0];
rsavenii(outfilename,h2,df2 );
|
github
|
philippboehmsturm/antx-master
|
createMontageImage.m
|
.m
|
antx-master/mritools/various/createMontageImage.m
| 13,004 |
utf_8
|
d53fdd8a041d1a92bf998314c3910fc6
|
function bigImage = montage(varargin)
%MONTAGE Display multiple image frames as rectangular montage.
% MONTAGE(FILENAMES) displays a montage of the images specified in
% FILENAMES. FILENAMES is an N-by-1 or 1-by-N cell array of file name
% strings. If the files are not in the current directory or in a
% directory on the MATLAB path, specify the full pathname. (See the
% IMREAD command for more information.) If one or more of the image files
% contains an indexed image, MONTAGE uses the colormap from the first
% indexed image file.
%
% By default, MONTAGE arranges the images so that they roughly form a
% square, but you can specify other arrangments using the 'Size'
% parameter (see below). MONTAGE creates a single image object to
% display the images.
%
% MONTAGE(I) displays a montage of all the frames of a multiframe image
% array I. I can be a sequence of binary, grayscale, or truecolor images.
% A binary or grayscale image sequence must be an M-by-N-by-1-by-K array.
% A truecolor image sequence must be an M-by-N-by-3-by-K array.
%
% MONTAGE(X,MAP) displays all the frames of the indexed image array X,
% using the colormap MAP for all frames. X is an M-by-N-by-1-by-K array.
%
% MONTAGE(..., PARAM1, VALUE1, PARAM2, VALUE2, ...) returns a customized
% display of an image montage, depending on the values of the optional
% parameter/value pairs. See Parameters below. Parameter names can be
% abbreviated, and case does not matter.
%
% H = MONTAGE(...) returns the handle of the single image object which
% contains all the frames displayed.
%
% Parameters
% ----------
% 'Size' A 2-element vector, [NROWS NCOLS], specifying the number
% of rows and columns in the montage. Use NaNs to have
% MONTAGE calculate the size in a particular dimension in
% a way that includes all the images in the montage. For
% example, if 'Size' is [2 NaN], MONTAGE creates a montage
% with 2 rows and the number of columns necessary to
% include all of the images. MONTAGE displays the images
% horizontally across columns.
%
% Default: MONTAGE calculates the rows and columns so the
% images in the montage roughly form a square.
%
% 'Indices' A numeric array that specifies which frames MONTAGE
% includes in the montage. MONTAGE interprets the values
% as indices into array I or cell array FILENAMES. For
% example, to create a montage of the first four frames in
% I, use this syntax:
%
% montage(I,'Indices',1:4);
%
% Default: 1:K, where K is the total number of frames or
% image files.
%
% 'DisplayRange' A 1-by-2 vector, [LOW HIGH], that adjusts the display
% range of the images in the image array. The images must
% must be grayscale images. The value LOW (and any value
% less than LOW) displays as black, the value HIGH (and
% any value greater than HIGH) displays as white. If you
% specify an empty matrix ([]), MONTAGE uses the minimum
% and maximum values of the images to be displayed in the
% montage as specified by 'Indices'. For example, if
% 'Indices' is 1:K and the 'Display Range' is set to [],
% MONTAGE displays the minimum value in of the image array
% (min(I(:)) as black, and displays the maximum value
% (max(I(:)) as white.
%
% Default: Range of the datatype of the image array.
%
% Class Support
% -------------
% A grayscale image array can be uint8, logical, uint16, int16, single,
% or double. An indexed image array can be logical, uint8, uint16,
% single, or double. MAP must be double. A truecolor image array can
% be uint8, uint16, single, or double. The output is a handle to the
% image object produced by MONTAGE.
%
% Example 1
% ---------
% This example creates a montage from a series of images in ten files.
% The montage has two rows and five columns. Use the DisplayRange
% parameter to highlight structures in the image.
%
% fileFolder = fullfile(matlabroot,'toolbox','images','imdemos');
% dirOutput = dir(fullfile(fileFolder,'AT3_1m4_*.tif'));
% fileNames = {dirOutput.name}'
% montage(fileNames, 'Size', [2 5]);
%
% figure, montage(fileNames, 'Size', [2 5], ...
% 'DisplayRange', [75 200]);
%
% Example 2
% ---------
% This example shows you how to customize the number of images in the
% montage.
%
% % Create a default montage.
% load mri
% montage(D, map)
%
% % Create a new montage containing only the first 9 images.
% figure
% montage(D, map, 'Indices', 1:9);
%
% See also IMMOVIE, IMSHOW, IMPLAY.
% Copyright 1993-2007 The MathWorks, Inc.
% $Revision: 1.1.8.8 $ $Date: 2007/06/04 21:11:07 $
[I,cmap,mSize,indices,displayRange] = parse_inputs(varargin{:});
if isempty(indices) || isempty(I)
hh = imshow([]);
if nargout > 0
h = hh;
end
return;
end
% Function Scope
nFrames = numel(indices);
nRows = size(I,1);
nCols = size(I,2);
montageSize = calculateMontageSize(mSize);
bigImage = createMontageImage;
% if isempty(cmap)
% if isempty(displayRange)
% num = numel(I(:,:,:,indices));
% displayRange(1) = min(reshape(I(:,:,:,indices),[1 num]));
% displayRange(2) = max(reshape(I(:,:,:,indices),[1 num]));
% end
% hh = imshow(bigImage, displayRange);
% else
% hh = imshow(bigImage,cmap);
% end
%
% if nargout > 0
% h = hh;
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function montageSize = calculateMontageSize(mSize)
if isempty(mSize) || all(isnan(mSize))
%Calculate montageSize for the user
% Estimate nMontageColumns and nMontageRows given the desired
% ratio of Columns to Rows to be one (square montage).
aspectRatio = 1;
montageCols = sqrt(aspectRatio * nRows * nFrames / nCols);
% Make sure montage rows and columns are integers. The order in
% the adjustment matters because the montage image is created
% horizontally across columns.
montageCols = ceil(montageCols);
montageRows = ceil(nFrames / montageCols);
montageSize = [montageRows montageCols];
elseif any(isnan(mSize))
montageSize = mSize;
nanIdx = isnan(mSize);
montageSize(nanIdx) = ceil(nFrames / mSize(~nanIdx));
elseif prod(mSize) < nFrames
eid = sprintf('Images:%s:sizeTooSmall', mfilename);
error(eid, ...
'SIZE must be big enough to include all frames in I.');
else
montageSize = mSize;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function b = createMontageImage
nMontageRows = montageSize(1);
nMontageCols = montageSize(2);
nBands = size(I, 3);
sizeOfBigImage = [nMontageRows*nRows nMontageCols*nCols nBands 1];
if islogical(I)
b = false(sizeOfBigImage);
else
b = zeros(sizeOfBigImage, class(I));
end
rows = 1 : nRows;
cols = 1 : nCols;
k = 1;
for i = 0 : nMontageRows-1
for j = 0 : nMontageCols-1,
if k <= nFrames
b(rows + i * nRows, cols + j * nCols, :) = ...
I(:,:,:,indices(k));
else
return;
end
k = k + 1;
end
end
end
end %MONTAGE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I,cmap,montageSize,idxs,displayRange] = parse_inputs(varargin)
iptchecknargin(1, 8, nargin, mfilename);
% initialize variables
cmap = [];
montageSize = [];
charStart = find(cellfun('isclass', varargin, 'char'));
if iscell(varargin{1})
%MONTAGE(FILENAMES.,..)
[I,cmap] = getImagesFromFiles(varargin{1});
else
%MONTAGE(I,...) or MONTAGE(X,MAP,...)
I = varargin{1};
iptcheckinput(varargin{1}, ...
{'uint8' 'double' 'uint16' 'logical' 'single' 'int16'}, {}, ...
mfilename, 'I, BW, or RGB', 1);
end
nframes = size(I,4);
displayRange = getrangefromclass(I);
idxs = 1:nframes;
if isempty(charStart)
%MONTAGE(FILENAMES), MONTAGE(I) or MONTAGE(X,MAP)
if nargin == 2
%MONTAGE(X,MAP)
cmap = validateColormapSyntax(I,varargin{2});
end
return;
end
charStart = charStart(1);
if charStart == 3
%MONTAGE(X,MAP,Param1,Value1,...)
cmap = validateColormapSyntax(I,varargin{2});
end
paramStrings = {'Size', 'Indices', 'DisplayRange'};
for k = charStart:2:nargin
param = lower(varargin{k});
inputStr = iptcheckstrs(param, paramStrings, mfilename, 'PARAM', k);
valueIdx = k + 1;
if valueIdx > nargin
eid = sprintf('Images:%s:missingParameterValue', mfilename);
error(eid, ...
'Parameter ''%s'' must be followed by a value.', ...
inputStr);
end
switch (inputStr)
case 'Size'
montageSize = varargin{valueIdx};
iptcheckinput(montageSize,{'numeric'},...
{'vector','positive'}, ...
mfilename, 'Size', valueIdx);
if numel(montageSize) ~= 2
eid = sprintf('Images:%s:invalidSize',mfilename);
error(eid, 'Size must be a 2-element vector.');
end
montageSize = double(montageSize);
case 'Indices'
idxs = varargin{valueIdx};
iptcheckinput(idxs, {'numeric'},...
{'vector','integer','nonnan'}, ...
mfilename, 'Indices', valueIdx);
invalidIdxs = ~isempty(idxs) && ...
any(idxs < 1) || ...
any(idxs > nframes);
if invalidIdxs
eid = sprintf('Images:%s:invalidIndices',mfilename);
error(eid, ...
'An index in INDICES cannot be less than 1 %s', ...
'or greater than the number of frames in I.');
end
idxs = double(idxs);
case 'DisplayRange'
displayRange = varargin{valueIdx};
displayRange = checkDisplayRange(displayRange, mfilename);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cmap = validateColormapSyntax(I,cmap)
if isa(I,'int16')
eid = sprintf('Images:%s:invalidIndexedImage',mfilename);
error(eid, 'An indexed image can be uint8, uint16, %s', ...
'double, single, or logical.');
end
iptcheckinput(cmap,{'double'},{},mfilename,'MAP',1);
if size(cmap,1) == 1 && prod(cmap) == numel(I)
% MONTAGE(D,[M N P]) OBSOLETE
eid = sprintf('Images:%s:obsoleteSyntax',mfilename);
error(eid, ...
'MONTAGE(D,[M N P]) is an obsolete syntax.\n%s', ...
'Use multidimensional arrays to represent multiframe images.');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I, map] = getImagesFromFiles(fileNames)
if isempty(fileNames)
eid = sprintf('Images:%s:invalidType', mfilename);
msg = 'FILENAMES must be a cell array of strings.';
error(eid, msg);
end
nframes = length(fileNames);
[img, map] = getImageFromFile(fileNames{1}, mfilename);
classImg = class(img);
sizeImg = size(img);
if length(sizeImg) > 2 && sizeImg(3) == 3
nbands = 3;
else
nbands = 1;
end
sizeImageArray = [sizeImg(1) sizeImg(2) nbands nframes];
if islogical(img)
I = false(sizeImageArray);
else
I = zeros(sizeImageArray, classImg);
end
I(:,:,:,1) = img;
for k = 2 : nframes
[img,tempmap] = getImageFromFile(fileNames{k}, mfilename);
if ~isequal(size(img),sizeImg)
eid = sprintf('Images:%s:imagesNotSameSize', mfilename);
error(eid, ...
'FILENAMES must contain images that are the same size.');
end
if ~strcmp(class(img),classImg)
eid = sprintf('Images:%s:imagesNotSameClass', mfilename);
error(eid, ...
'FILENAMES must contain images that have the same class.');
end
if isempty(map) && ~isempty(tempmap)
map = tempmap;
end
I(:,:,:,k) = img;
end
end
|
github
|
philippboehmsturm/antx-master
|
rreslice.m
|
.m
|
antx-master/mritools/various/rreslice.m
| 1,074 |
utf_8
|
3555e08dc6559b72c65642fe2c68d030
|
function rreslice(PI,PO,dim,mat,hld)
% FORMAT reslice(PI,PO,dim,mat,hld)
% PI - input filename
% PO - output filename
% dim - 1x3 matrix of image dimensions
% mat - 4x4 affine transformation matrix mapping
% from vox to mm (for output image).
% To define M from vox and origin, then
% off = -vox.*origin;
% M = [vox(1) 0 0 off(1)
% 0 vox(2) 0 off(2)
% 0 0 vox(3) off(3)
% 0 0 0 1];
%
% hld - interpolation method.
%___________________________________________________________________________
% @(#)JohnsGems.html 1.42 John Ashburner 05/02/02
VI = spm_vol(PI);
VO = VI;
VO.fname = deblank(PO);
VO.mat = mat;
VO.dim(1:3) = dim;
VO = spm_create_vol(VO);
for x3 = 1:VO.dim(3),
% M = inv(spm_matrix([0 0 -x3 0 0 0 1 1 1])*inv(VO.mat)*VI.mat);
M=mat;
v = spm_slice_vol(VI,M,VO.dim(1:2),hld);
VO = spm_write_plane(VO,v,x3);
end;
|
github
|
philippboehmsturm/antx-master
|
pnum.m
|
.m
|
antx-master/mritools/various/pnum.m
| 492 |
utf_8
|
bb7b8dcf3645f818b1bddc66a601f3f9
|
% get number as string within a 'n-digits zeros string', such as '001, 002,003'
% function str=pnum(nr,ndigits)
% nr: number
% ndigits: number of digits
% example:
% str=pnum(112,5); %%str is 00112; e.g. 5digits string with the number 112
function str=pnum(nr,digits)
% nu=3
str=repmat('0',[1 digits]);
str(end-length(num2str(nr))+1:end)=num2str(nr);
% for i=1:100
% og2=og;
% og2(end-length(num2str(i))+1:end)=num2str(i);
% disp(og2);
% end
|
github
|
philippboehmsturm/antx-master
|
pwf.m
|
.m
|
antx-master/mritools/various/pwf.m
| 2,039 |
utf_8
|
5d1d1331f027ac1ddddf2f75d4a6324e
|
function varargout =pwf
%PWF Show+CLIPBOARD filename+PATH+description of Editor's on top file
% % % print working file (print currently opened file in editor)
try
% Matlab 7
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jEditor = desktop.getGroupContainer('Editor').getTopLevelAncestor;
% we get a com.mathworks.mde.desk.MLMultipleClientFrame object
catch
% Matlab 6
% Unfortunately, we can't get the Editor handle from the Desktop handle in Matlab 6:
%desktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop;
% So here's the workaround for Matlab 6:
openDocs = com.mathworks.ide.editor.EditorApplication.getOpenDocuments; % a java.util.Vector
firstDoc = openDocs.elementAt(0); % a com.mathworks.ide.editor.EditorViewContainer object
jEditor = firstDoc.getParent.getParent.getParent;
% we get a com.mathworks.mwt.MWTabPanel or com.mathworks.ide.desktop.DTContainer object
end
title = jEditor.getTitle;
currentFilename = char(title.replaceFirst('Editor - ',''));
txt=help(currentFilename);
txt=txt(1:min(strfind(txt,char(10))));
out=[' ' currentFilename ' - ' txt];
disp(out);
clipboard('copy',out);
txt=help(currentFilename);
txt=txt(1:min(strfind(txt,char(10))));
% out=[' ' currentFilename ' - ' txt];
[pa fi ext]=fileparts(currentFilename);
stuff=[[fi ext ' - ' txt] sprintf('\t\t') currentFilename ];
clipboard('copy',stuff);
disp(stuff);
if nargout~=0
varargout{1}=out;
end
return
%% get all open files
if 0
% Alternative #1:
edhandle = com.mathworks.mlservices.MLEditorServices;
allEditorFilenames = char(edhandle.builtinGetOpenDocumentNames);
% Alternative #2:
openFiles = desktop.getWindowRegistry.getClosers.toArray.cell;
allEditorFilenames = cellfun(@(c)c.getTitle.char,openFiles,'un',0);
end
% % Equivalent actions via properties:
% set(jEditor, 'Resizable', 'on');
% set(jEditor, 'StatusText', 'testing 123...');
% set(jEditor, 'Title', 'This is the Matlab Editor');
%
|
github
|
philippboehmsturm/antx-master
|
maskdata.m
|
.m
|
antx-master/mritools/various/maskdata.m
| 1,241 |
utf_8
|
1aa1066ace0b21a7ac9828816a210135
|
function [fileout h x ]=maskdata(file,cords,dimens,operation,assign, suffix )
%% mask data in file based given 3cooredinates, the dimension to mask, the operation and assignment
% file = filename
% cords =standard space coordinates, 3 values ,e.g [ 0 0 0]
% dimens =dimension where operation and assignment is directed
% operation=(string) mathematical relation <,>,=>...~=,
% assign =value to be assigned , e.g 0
% suffix = suffic to be assigned
% example:
% maskData('_Atpl_mouseatlasNew_masked.nii',[0 0 0],1,'<',0, '_leftTest' );
%%explanation: %set mask on left hemisphere, 1..refers to first dimension,
%%values below 0 (first enty in cords) becomes zero
if 0
cords=[0 0 0 ]
operation='>'
assign =0;
dimens =1;
suffix='_test'
end
% ha=spm_vol(file);
% a=(spm_read_vols(ha));
[ha a xyz]=rgetnii(file );
xyz=xyz';
idx=round(mni2idx(cords, ha,'mni2idx'));
a2=a(:);
idx=[];
% idx2=find(xyz(:,dimens)>cords(dimens));
eval(['idx2=find(xyz(:,dimens)' operation 'cords(dimens));' ]);
eval('a2(idx2)=assign;' );
ha3=ha;
a3=reshape(a2, ha.dim);
fileout=strrep(file,'.nii',[suffix '.nii']);
rsavenii(fileout,ha3,a3 );
|
github
|
philippboehmsturm/antx-master
|
EditorMacro.m
|
.m
|
antx-master/mritools/graphics/EditorMacro.m
| 44,535 |
utf_8
|
f122d01b23833c7a6f52969105d5e749
|
function [bindingsList, actionsList] = EditorMacro(keystroke, macro, macroType)
% EditorMacro assigns a macro to a keyboard key-stroke in the Matlab-editor
%
% Syntax:
% [bindingsList, actionsList] = EditorMacro(keystroke, macro, macroType)
% [bindingsList, actionsList] = EditorMacro(bindingsList)
%
% Description:
% EditorMacro assigns the specified MACRO to the requested keyboard
% KEYSTROKE, within the context of the Matlab Editor and Command Window.
%
% KEYSTROKE is a string representation of the keyboard combination.
% Special modifiers (Alt, Ctrl or Control, Shift, Meta, AltGraph) are
% recognized and should be separated with a space, dash (-), plus (+) or
% comma (,). At least one of the modifiers should be specified, otherwise
% very weird things will happen...
% For a full list of supported keystrokes, see:
% <a href="http://tinyurl.com/2s63e9">http://java.sun.com/javase/6/docs/api/java/awt/event/KeyEvent.html</a>
% If KEYSTROKE was already defined, then it will be updated (overridden).
%
% MACRO should be in one of Matlab's standard callback formats: 'string',
% @FunctionHandle or {@FunctionHandle,arg1,...}, or any of several hundred
% built-in editor action-names - read MACROTYPE below for a full
% description. To remove a KEYSTROKE-MACRO definition, simply enter an
% empty MACRO ([], {} or '').
%
% MACROTYPE is an optional input argument specifying the type of action
% that MACRO is expected to do:
%
% - 'text' (=default value) indicates that if the MACRO is a:
% 1. 'string': this string will be inserted as-is into the current
% editor caret position (or replace the selected editor text).
% Multi-line strings can be set using embedded \n's (example:
% 'Multi-line\nStrings'). This can be used to insert generic
% comments or code templates (example: 'try \n catch \n end').
% 2. @FunctionHandle - the specified function will be invoked with
% two input arguments: the editorPane object and the eventData
% object (the KEYSTROKE event details). FunctionHandle is
% expected to return a string which will then be inserted into
% the editor document as expained above.
% 3. {@FunctionHandle,arg1,...} - like #2, but the function will be
% called with the specified arg1+ as input args #3+, following
% the editorPane and eventData args.
%
% - 'run' indicates that MACRO should be invoked as a Matlab command,
% just like any regular Matlab callback. The accepted MACRO
% formats and function input args are exactly like for 'text'
% above, except that no output string is expected and no text
% insertion/replacement will be done (unless specifically done
% within the invoked MACRO command/function). This MACROTYPE is
% useful for closing/opening files, moving to another document
% position and any other non-textual action.
%
% In addition, this MACROTYPE accepts all available (built-in)
% editor action names. Valid action names can be listed by
% requesting the ACTIONSLIST output argument.
%
% BINDINGSLIST = EditorMacro returns the list of currently-defined
% KEYSTROKE bindings as a 4-columned cell array: {keystroke, macro, type,
% class}. The class information indicates a built-in action ('editor menu
% action', 'editor native action', 'cmdwin native action' or 'cmdwin menu
% action') or a user-defined action ('text' or 'user-defined macro').
%
% BINDINGSLIST = EditorMacro(KEYSTROKE) returns the bindings list for
% the specified KEYSTROKE as a 4-columned cell array: {keystroke, macro,
% type, class}.
%
% BINDINGSLIST = EditorMacro(KEYSTROKE,MACRO) returns the bindings list
% after defining a specific KEYSTROKE-MACRO binding.
%
% EditorMacro(BINDINGSLIST) can be used to set a bunch of key bindings
% using a single command. BINDINGSLIST is the cell array returned from
% a previous invocation of EditorMacro, or by manual construction (just
% be careful to set the keystroke strings correctly!). Only non-native
% bindings are updated in this bulk mode of operation.
%
% [BINDINGSLIST, ACTIONSLIST] = EditorMacro(...) returns in ACTIONSLIST a
% 3-columned cell array of all available built-in actions and currently-
% associated key-biding(s): {actionName, keyBinding(s), class}.
%
% Examples:
% bindingsList = EditorMacro; % get list of current key-bindings
% bindingsList = EditorMacro('ctrl r'); % get list of bindings for <Ctrl>-R
% [bindings,actions] = EditorMacro; % get list of available built-in action-names
% EditorMacro('Ctrl Shift C', '%%% Main comment %%%\n% \n% \n% \n');
% EditorMacro('Alt-x', 'try\n % Main code here\ncatch\n % Exception handling here\nend');
% EditorMacro('Ctrl-Alt C', @myCallbackFunction); % myCallbackFunction returns a string to insert
% EditorMacro('Alt control t', @(a,b)datestr(now), 'text'); % insert current timestamp
% EditorMacro('Shift-Control d', {@computeDiameter,3.14159}, 'run');
% EditorMacro('Alt L', 'to-lower-case', 'run') % Built-in action: convert text to lowercase
% EditorMacro('ctrl D','open-selection','run') % Override default Command-Window action (=delete)
% % to behave as in the Editor (=open selected file)
%
% Known limitations (=TODO for future versions):
% 1. Multi-keystroke bindings (e.g., 'alt-U,L') are not supported
% 2. In Matlab 6, macro insertions are un-undo-able (ok in Matlab 7)
% 3. Key bindings are sometimes lost when switching between a one-document
% editor and a two-document one (i.e., adding/closing the second doc)
% 4. Key bindings are not saved between editor sessions
% 5. In split-pane mode, when inserting a macro on the secondary (right/
% bottom) pane, then both panes (and the actual document) are updated
% but the secondary pane does not display the inserted macro (the
% primary pane looks ok).
% 6. Native menu/editor/command-window actions cannot be updated in bulk
% mode (EditorMacro(BINDINGSLIST)) - only one at a time.
% 7. Key-bindings may be fogotten when switching between docked/undocked
% editor or between the Command-Window and other docked desktop panes
% (such as Command History, Profiler etc.)
% 8. In Matlab 6, actions are not supported: only user-defined text/macro
%
% Bugs and suggestions:
% Please send to Yair Altman (altmany at gmail dot com)
%
% Warning:
% This code heavily relies on undocumented and unsupported Matlab
% functionality. It works on Matlab 6 & 7+, but use at your own risk!
%
% A technical description of the implementation can be found at:
% <a href="http://undocumentedmatlab.com/blog/EditorMacro/">http://UndocumentedMatlab.com/blog/EditorMacro/</a>
%
% Change log:
% 2011-01-31: Fixes for R2011a
% 2009-10-26: Fixes for Matlab 6
% 2009-08-19: Support for command-window actions; use EDT for text replacement
% 2009-08-11: Several fixes; support for native/menu actions (idea by Perttu Ranta-aho)
% 2009-07-03: Fixed Matlab 6 edge-case; Automatically detect macro functions that do not accept the expected two input args
% 2009-07-01: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a>
% Programmed by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.6 $ $Date: 2011/01/31 20:47:25 $
persistent appdata
try
% Check input args
if nargin == 2
macroType = 'text';
elseif nargin == 3 & ~ischar(macroType) %#ok Matlab 6 compatibility
myError('YMA:EditorMacro:badMacroType','MacroType must be ''text'', ''run'' or ''native''');
elseif nargin > 3
myError('YMA:EditorMacro:tooManyArgs','too many input argument');
end
% Try to get the editor's Java handle
jEditor = getJEditor;
% ...and the editor's main documents container handle
jMainPane = getJMainPane(jEditor);
hEditorPane = getEditorPane(jMainPane.getComponent(0)); % first document
% ...and the desktop's Command Window handle
try
jCmdWin = [];
%mde = jMainPane.getRootPane.getParent.getDesktop;
mde = com.mathworks.mde.desk.MLDesktop.getInstance; % different in ML6!!!
hCmdWin = mde.getClient('Command Window');
jCmdWin = hCmdWin.getComponent(0).getComponent(0).getComponent(0); % com.mathworks.mde.cmdwin.XCmdWndView
jCmdWin = handle(jCmdWin, 'CallbackProperties');
catch
% Maybe ML6 or... - never mind...
end
% Now try to get the persistent list of macros
try
appdata = getappdata(jEditor,'EditorMacro');
catch
% never mind - we will use the persistent object instead...
end
% If no EditorMacro has been set yet
if isempty(appdata)
% Set the initial binding hashtable
appdata = {}; %java.util.Hashtable is better but can't extract {@function}...
% Add editor native action bindings to the bindingsList
edActionsMap = getAccelerators(hEditorPane); % =getAccelerators(hEditorPane.getActiveTextComponent);
appdata.bindings = getBindings({},edActionsMap,'editor native action');
% Add CW native action bindings to the bindingsList
cwActionsMap = getAccelerators(jCmdWin);
appdata.bindings = getBindings(appdata.bindings,cwActionsMap,'cmdwin native action');
% Add editor menu action bindings to the bindingsList
appdata.edMenusMap = getMenuShortcuts(jMainPane);
appdata.bindings = getBindings(appdata.bindings,appdata.edMenusMap,'editor menu action');
% Add CW menu action bindings to the bindingsList
appdata.cwMenusMap = getMenuShortcuts(jCmdWin);
appdata.bindings = getBindings(appdata.bindings,appdata.cwMenusMap,'cmdwin menu action');
% Loop over all the editor's currently-open documents
for docIdx = 1 : jMainPane.getComponentCount
% Instrument these documents to catch user keystrokes
instrumentDocument([],[],jMainPane.getComponent(docIdx-1),jEditor,appdata);
end
% Update the editor's ComponentAdded callback to also instrument new documents
set(jMainPane,'ComponentAddedCallback',{@instrumentDocument,[],jEditor,appdata})
if isempty(get(jMainPane,'ComponentAddedCallback'))
pause(0.1);
set(jMainPane,'ComponentAddedCallback',{@instrumentDocument,[],jEditor,appdata})
end
% Also instrument the CW to catch user keystrokes
set(jCmdWin, 'KeyPressedCallback', {@keyPressedCallback,jEditor,appdata,jCmdWin});
end
% If any macro setting is requested
if nargin
% Update the bindings list with the new key binding
if nargin > 1
appdata = updateBindings(appdata,keystroke,macro,macroType,jMainPane,jCmdWin);
setappdata(jEditor,'EditorMacro',appdata);
elseif iscell(keystroke) & (isempty(keystroke) | size(keystroke,2)==4) %#ok Matlab 6 compatibility
appdata = keystroke; % passed updated bindingsList as input arg
setappdata(jEditor,'EditorMacro',appdata);
elseif ischar(keystroke) | isa(keystroke,'javax.swing.KeyStroke') %#ok Matlab 6 compatibility
setappdata(jEditor,'EditorMacro',appdata);
keystroke = normalizeKeyStroke(keystroke);
bindingIdx = strmatch(keystroke,appdata.bindings(:,1),'exact');
appdata.bindings = appdata.bindings(bindingIdx,:); % only return matching bindings
else
myError('YMA:EditorMacro:invalidBindingsList','invalid BINDINGSLIST input argument');
end
end
% Check if output is requested
if nargout
if ~iscell(appdata.bindings)
appdata.bindings = {};
end
bindingsList = appdata.bindings;
% Return the available actionsList
if nargout > 1
% Start with the native editor actions
actionsList = listActionsMap(hEditorPane);
try [actionsList{:,3}] = deal('editor native action'); catch, end
% ...add the desktop's CW native actions...
cwActionsList = listActionsMap(jCmdWin);
try [cwActionsList{:,3}] = deal('cmdwin native action'); catch, end
actionsList = [actionsList; cwActionsList];
% ...and finally add the menu actions
try
menusList = appdata.edMenusMap(:,[2,1]); % {action,keystroke}
try [menusList{:,3}] = deal('editor menu action'); catch, end
actionsList = [actionsList; menusList];
catch
% never mind...
end
try
menusList = appdata.cwMenusMap(:,[2,1]);
try [menusList{:,3}] = deal('cmdwin menu action'); catch, end
actionsList = [actionsList; menusList];
catch
% never mind...
end
end
end
% Error handling
catch
handleError;
end
%% Get the current list of key-bindings
function bindings = getBindings(bindings,actionsMap,groupName)
try
for bindingIdx = 1 : size(actionsMap,1)
ks = actionsMap{bindingIdx,1};
if ~isempty(ks)
actionName = actionsMap{bindingIdx,2};
[bindings(end+1,:)] = {ks,actionName,'run',groupName}; %#ok grow
end
end
catch
% never mind...
end
%% Modify native shortcuts
function bindingsList = nativeShortcuts(keystroke, macro, jMainPane)
% Note: this function is unused
hEditorPane = getEditorPane(jMainPane.getComponent(0)); % first document
switch lower(keystroke(1:5))
case 'listn'
% List all active accelerators
bindingsList = getAccelerators(hEditorPane.getActiveTextComponent);
if ~nargout
for ii = 1 : size(bindingsList,1)
disp(sprintf('%-35s %s',bindingsList{ii,:}))
end
end
case 'lista'
% List all available actions
bindingsList = listActionsMap(hEditorPane,nargout);
otherwise
% Bind native action
bindingsList = getNativeActions(hEditorPane);
if ~ismember(macro,bindingsList) & ~isempty(macro) %#ok Matlab 6 compatibility
myError('YMA:EditorMacro:invalidNativeAction','invalid Native Action');
end
[keystroke,jKeystroke] = normalizeKeyStroke(keystroke);
%jkeystroke = javax.swing.KeyStroke.getKeyStroke(keystroke);
for docIdx = 1 : jMainPane.getComponentCount
% Instrument these documents to catch user keystrokes
hEditorPane = getEditorPane(jMainPane.getComponent(docIdx-1));
inputMap = hEditorPane.getInputMap;
removeShortcut(inputMap,jKeystroke);
if ~isempty(macro)
action = hEditorPane.getActionMap.get(macro);
inputMap.put(jKeystroke,action);
end
end
removeMenuShortcut(jMainPane,keystroke);
end
%% Get/list all available key-bindings for all the possible actions
function bindingsList = listActionsMap(hEditorPane,nargoutFlag)
try
bindingsList = getNativeActions(hEditorPane);
try
% Editor accelerators are stored in the activeTextComponent
accellerators = getAccelerators(hEditorPane.getActiveTextComponent);
catch
% The CW doesn't have an activeTextComponent...
accellerators = getAccelerators(hEditorPane);
end
for ii = 1 : size(bindingsList,1)
actionKeys = accellerators(strcmpi(accellerators(:,2),bindingsList{ii}),1);
if numel(actionKeys)==1
actionKeys = actionKeys{1};
keysStr = actionKeys;
elseif isempty(actionKeys)
actionKeys = [];
keysStr = ' [not assigned]';
else % multiple keys assigned
keysStr = strcat(char(actionKeys),',')';
keysStr = keysStr(:)'; % =reshape(keysStr,1,numel(keysStr));
keysStr = strtrim(strrep(keysStr,',',', '));
keysStr = regexprep(keysStr,'\s+',' ');
keysStr = keysStr(1:end-1); % remove trailing ','
end
bindingsList{ii,2} = actionKeys;
if nargin > 1 & ~nargoutFlag %#ok Matlab 6 compatibility
%disp(bindingsList)
disp(sprintf('%-35s %s',bindingsList{ii,1},keysStr))
end
end
catch
% never mind...
end
%% Get all available actions (even those without any key-binding)
function actionNames = getNativeActions(hEditorPane)
try
actionNames = {};
actionKeys = hEditorPane.getActionMap.allKeys;
actionNames = cellfun(@char,cell(actionKeys),'UniformOutput',false);
actionNames = sort(actionNames);
catch
% never mind...
end
%% Get all active native shortcuts
function accelerators = getAccelerators(hEditorPane)
try
accelerators = cell(0,2);
inputMap = hEditorPane.getInputMap;
inputKeys = inputMap.allKeys;
accelerators = cell(numel(inputKeys),2);
for ii = 1 : numel(inputKeys)
accelerators(ii,:) = {char(inputKeys(ii)), char(inputMap.get(inputKeys(ii)))};
end
accelerators = sortrows(accelerators,1);
catch
% never mind...
end
%% Remove shortcut from inputMap
function removeShortcut(inputMap,keystroke)
if ~isa(keystroke,'javax.swing.KeyStroke')
keystroke = javax.swing.KeyStroke.getKeyStroke(keystroke);
end
inputMap.remove(keystroke);
%keys = inputMap.allKeys;
%for ii = 1:length(keys)
% if keys(ii) == keystroke
% % inputMap.remove(keystroke);
% inputMap.put(keystroke,[]); %,null(1));
% return
% end
%end
try
% keystroke not found - try to find it in the parent inputMap...
removeShortcut(inputMap.getParent,keystroke)
catch
% Never mind
end
%% Get the list of all menu actions
function menusMap = getMenuShortcuts(jMainPane)
try
menusMap = {};
jRootPane = jMainPane.getRootPane;
jMenubar = jRootPane.getMenuBar; %=jRootPane.getComponent(1).getComponent(1);
for menuIdx = 1 : jMenubar.getMenuCount
% top-level menus should be treated differently than sub-menus
jMenu = jMenubar.getMenu(menuIdx-1);
menusMap = getMenuShortcuts_recursive(jMenu,menusMap);
end
catch
% Never mind
end
%% Recursively get the list of all menu actions
function menusMap = getMenuShortcuts_recursive(jMenu,menusMap)
try
numMenuComponents = getNumMenuComponents(jMenu);
for child = 1 : numMenuComponents
menusMap = getMenuShortcuts_recursive(jMenu.getMenuComponent(child-1),menusMap);
end
catch
% Probably a simple menu item, not a sub-menu - add it to the menusMap
try
accelerator = char(jMenu.getAccelerator);
if isempty(accelerator)
accelerator = []; % ''=>[]
end
[menusMap(end+1,:)] = {accelerator, char(jMenu.getActionCommand), jMenu};
catch
% maybe a separator or something strange... - ignore
end
end
%% Remove shortcut from Menu items inputMap
function menusMap = removeMenuShortcut(menusMap,keystroke)
try
keystroke = normalizeKeyStroke(keystroke);
map = cellfun(@char,menusMap(:,1),'un',0);
oldBindingIdx = strmatch(keystroke,map,'exact');
if ~isempty(oldBindingIdx)
menusMap{oldBindingIdx,1} = '';
menusMap{oldBindingIdx,3}.setAccelerator([]);
end
catch
% never mind...
end
%% Remove shortcut from Menu items inputMap
function removeMenuShortcut_old(jMainPane,keystroke)
% Note: this function was replaced by removeMenuShortcut()
try
% Try to remove any corresponding menu-item accelerator
jRootPane = jMainPane.getRootPane;
jMenubar = jRootPane.getMenuBar; %=jRootPane.getComponent(1).getComponent(1);
if ~isa(keystroke,'javax.swing.KeyStroke')
keystroke = javax.swing.KeyStroke.getKeyStroke(keystroke);
end
for menuIdx = 1 : jMenubar.getMenuCount
% top-level menus should be treated differently than sub-menus
jMenu = jMenubar.getMenu(menuIdx-1);
if removeMenuShortcut_recursive(jMenu,keystroke)
return;
end
end
catch
% never mind...
end
%% Recursively remove shortcut from Menu items inputMap
function found = removeMenuShortcut_recursive(jMenu,keystroke)
try
% Try to remove any corresponding menu-item accelerator
found = 0;
if ~isempty(jMenu.getActionForKeyStroke(keystroke))
jMenu.setAccelerator([]);
found = 1;
return;
end
% Not found - try to dig further
try
numMenuComponents = getNumMenuComponents(jMenu);
for child = 1 : numMenuComponents
found = removeMenuShortcut_recursive(jMenu.getMenuComponent(child-1),keystroke);
if found
return;
end
end
catch
% probably a simple menu item, not a sub-menu - ignore
%a=1; % debuggable breakpoint...
end
catch
% never mind...
end
%% Get the number of menu sub-elements
function numMenuComponents = getNumMenuComponents(jcontainer)
% The following line will raise an Exception for anything except menus
numMenuComponents = jcontainer.getMenuComponentCount;
% No error so far, so this must be a menu container...
% Note: Menu subitems are not visible until the top-level (root) menu gets initial focus...
% Try several alternatives, until we get a non-empty menu (or not...)
% TODO: Improve performance - this takes WAY too long...
if jcontainer.isTopLevelMenu & (numMenuComponents==0)
jcontainer.requestFocus;
numMenuComponents = jcontainer.getMenuComponentCount;
if (numMenuComponents == 0)
drawnow; pause(0.001);
numMenuComponents = jcontainer.getMenuComponentCount;
if (numMenuComponents == 0)
jcontainer.setSelected(true);
numMenuComponents = jcontainer.getMenuComponentCount;
if (numMenuComponents == 0)
drawnow; pause(0.001);
numMenuComponents = jcontainer.getMenuComponentCount;
if (numMenuComponents == 0)
jcontainer.doClick; % needed in order to populate the sub-menu components
numMenuComponents = jcontainer.getMenuComponentCount;
if (numMenuComponents == 0)
drawnow; %pause(0.001);
numMenuComponents = jcontainer.getMenuComponentCount;
jcontainer.doClick; % close menu by re-clicking...
if (numMenuComponents == 0)
drawnow; %pause(0.001);
numMenuComponents = jcontainer.getMenuComponentCount;
end
else
% ok - found sub-items
% Note: no need to close menu since this will be done when focus moves to another window
%jcontainer.doClick; % close menu by re-clicking...
end
end
end
jcontainer.setSelected(false); % de-select the menu
end
end
end
%% Get the Java editor component handle
function jEditor = getJEditor
jEditor = [];
try
% Matlab 7
jEditor = com.mathworks.mde.desk.MLDesktop.getInstance.getGroupContainer('Editor');
catch
% Matlab 6
try
%desktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop; % no use - can't get to the editor from here...
openDocs = com.mathworks.ide.editor.EditorApplication.getOpenDocuments; % a java.util.Vector
firstDoc = openDocs.elementAt(0); % a com.mathworks.ide.editor.EditorViewContainer object
jEditor = firstDoc.getParent.getParent.getParent; % a com.mathworks.mwt.MWTabPanel or com.mathworks.ide.desktop.DTContainer object
catch
myError('YMA:EditorMacro:noEditor','Cannot retrieve the Matlab editor handle - possibly no open editor');
end
end
if isempty(jEditor)
myError('YMA:EditorMacro:noEditor','Cannot retrieve the Matlab editor handle - possibly no open editor');
end
try
jEditor = handle(jEditor,'CallbackProperties');
catch
% never mind - might be Matlab 6...
end
%% Get the Java editor's main documents container handle
function jMainPane = getJMainPane(jEditor)
jMainPane = [];
try
v = version;
if (v(1) >= '7')
for childIdx = 1 : jEditor.getComponentCount
componentClassName = regexprep(jEditor.getComponent(childIdx-1).class,'.*\.','');
if any(strcmp(componentClassName,{'DTMaximizedPane','DTFloatingPane','DTTiledPane'}))
jMainPane = jEditor.getComponent(childIdx-1);
break;
end
end
if isa(jMainPane,'com.mathworks.mwswing.desk.DTFloatingPane')
jMainPane = jMainPane.getComponent(0); % a com.mathworks.mwswing.desk.DTFloatingPane$2 object
end
else
for childIdx = 1 : jEditor.getComponentCount
if isa(jEditor.getComponent(childIdx-1),'com.mathworks.mwt.MWGroupbox') | ...
isa(jEditor.getComponent(childIdx-1),'com.mathworks.ide.desktop.DTClientFrame') %#ok Matlab 6 compatibility
jMainPane = jEditor.getComponent(childIdx-1);
break;
end
end
end
catch
% Matlab 6 - ignore for now...
end
if isempty(jMainPane)
myError('YMA:EditorMacro:noMainPane','Cannot find the Matlab editor''s main document pane');
end
try
jMainPane = handle(jMainPane,'CallbackProperties');
catch
% never mind - might be Matlab 6...
end
%% Get EditorPane
function hEditorPane = getEditorPane(jDocPane)
try
% Matlab 7 TODO: good for ML 7.1-7.7: need to check other versions
jSyntaxTextPaneView = getDescendent(jDocPane,[0,0,1,0,0,0,0]);
if isa(jSyntaxTextPaneView,'com.mathworks.widgets.SyntaxTextPaneMultiView$1')
hEditorPane(1) = handle(getDescendent(jSyntaxTextPaneView.getComponent(1),[1,0,0]),'CallbackProperties');
hEditorPane(2) = handle(getDescendent(jSyntaxTextPaneView.getComponent(2),[1,0,0]),'CallbackProperties');
else
jEditorPane = getDescendent(jSyntaxTextPaneView,[1,0,0]);
hEditorPane = handle(jEditorPane,'CallbackProperties');
end
catch
% Matlab 6
hEditorPane = getDescendent(jDocPane,[0,0,0,0]);
if isa(hEditorPane,'com.mathworks.mwt.MWButton') % edge case
hEditorPane = getDescendent(jDocPane,[0,1,0,0]);
end
end
%% Internal error processing
function myError(id,msg)
v = version;
if (v(1) >= '7')
error(id,msg);
else
% Old Matlab versions do not have the error(id,msg) syntax...
error(msg);
end
%% Error handling routine
function handleError
v = version;
if v(1)<='6'
err.message = lasterr; %#ok no lasterror function...
else
err = lasterror; %#ok
end
try
err.message = regexprep(err.message,'Error .* ==> [^\n]+\n','');
catch
try
% Another approach, used in Matlab 6 (where regexprep is unavailable)
startIdx = findstr(err.message,'Error using ==> ');
stopIdx = findstr(err.message,char(10));
for idx = length(startIdx) : -1 : 1
idx2 = min(find(stopIdx > startIdx(idx))); %#ok ML6
err.message(startIdx(idx):stopIdx(idx2)) = [];
end
catch
% never mind...
end
end
if isempty(findstr(mfilename,err.message))
% Indicate error origin, if not already stated within the error message
err.message = [mfilename ': ' err.message];
end
if v(1)<='6'
while err.message(end)==char(10)
err.message(end) = []; % strip excessive Matlab 6 newlines
end
error(err.message);
else
rethrow(err);
end
%% Main keystroke callback function
function instrumentDocument(jObject,jEventData,jDocPane,jEditor,appdata) %#ok jObject is unused
try
if isempty(jDocPane)
% This happens when we get here via the jEditor's ComponentAddedCallback
% (when adding a new document pane)
try
% Matlab 7
jDocPane = jEventData.getChild;
catch
% Matlab 6
eventData = get(jObject,'ComponentAddedCallbackData');
jDocPane = eventData.child;
end
end
hEditorPane = getEditorPane(jDocPane);
% Note: KeyTypedCallback is called less frequently (i.e. better),
% ^^^^ but unfortunately it does not catch alt/ctrl combinations...
%set(hEditorPane, 'KeyTypedCallback', {@keyPressedCallback,jEditor,appdata,hEditorPane});
set(hEditorPane, 'KeyPressedCallback', {@keyPressedCallback,jEditor,appdata,hEditorPane});
pause(0.01); % needed in Matlab 6...
catch
% never mind - might be Matlab 6...
end
%% Recursively get the specified children
function child = getDescendent(child,listOfChildrenIdx)
if ~isempty(listOfChildrenIdx)
child = getDescendent(child.getComponent(listOfChildrenIdx(1)),listOfChildrenIdx(2:end));
end
%% Update the bindings list
function appdata = updateBindings(appdata,keystroke,macro,macroType,jMainPane,jCmdWin)
[keystroke,jKeystroke] = normalizeKeyStroke(keystroke);
%jKeystroke = javax.swing.KeyStroke.getKeyStroke(keystroke);
%appdata.put(keystroke,macro); %using java.util.Hashtable is better but can't extract {@function}...
try
oldBindingIdx = strmatch(keystroke,appdata.bindings(:,1),'exact');
appdata.bindings(oldBindingIdx,:) = []; % clear any possible old binding
catch
% ignore - possibly empty appdata
a=1; % debug point
end
% Remove native key-bindings from all editor documents / menu-items
try
for docIdx = 1 : jMainPane.getComponentCount
hEditorPane = getEditorPane(jMainPane.getComponent(docIdx-1));
inputMap = hEditorPane.getInputMap;
removeShortcut(inputMap,keystroke);
end
appdata.edMenusMap = removeMenuShortcut(appdata.edMenusMap,keystroke);
appdata.cwMenusMap = removeMenuShortcut(appdata.cwMenusMap,keystroke);
catch
% never mind...
end
try
if ~isempty(macro)
% Normalize the requested macro (if it's a string): '\n', ...
if ischar(macro)
macro = sprintf(strrep(macro,'%','%%'));
end
% Check & normalize the requested macroType
if ~ischar(macroType)
myError('YMA:EditorMacro:badMacroType','bad MACROTYPE input argument - must be a ''string''');
elseif isempty(macroType) | ~any(lower(macroType(1))=='rt') %#ok for Matlab6 compatibility
myError('YMA:EditorMacro:badMacroType','bad MACROTYPE input argument - must be ''text'' or ''run''');
elseif lower(macroType(1)) == 'r'
macroType = 'run';
macroClass = 'user-defined macro';
else
macroType = 'text';
macroClass = 'text';
end
% Check if specified macro is a native and/or menu action name
if ischar(macro) & macroType(1)=='r' %#ok Matlab 6 compatibility
% Check for editor native action name
actionFound = 0;
hEditorPane = getEditorPane(jMainPane.getComponent(0)); % first document
actionNames = getNativeActions(hEditorPane);
if any(strcmpi(macro,actionNames)) %#ok Matlab 6 compatibility
% Specified macro appears to be a valid native action name
for docIdx = 1 : jMainPane.getComponentCount
% Add requested action binding to all editor documents' inputMaps
hEditorPane = getEditorPane(jMainPane.getComponent(docIdx-1));
inputMap = hEditorPane.getInputMap;
%removeShortcut(inputMap,jKeystroke);
action = hEditorPane.getActionMap.get(macro);
inputMap.put(jKeystroke,action);
end
[appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'editor native action'};
actionFound = 1;
end
% Check for CW native action name
actionNames = getNativeActions(jCmdWin);
if any(strcmpi(macro,actionNames)) %#ok Matlab 6 compatibility
% Specified macro appears to be a valid native action name
% Add requested action binding to the CW inputMap
inputMap = jCmdWin.getInputMap;
%removeShortcut(inputMap,jKeystroke);
action = jCmdWin.getActionMap.get(macro);
inputMap.put(jKeystroke,action);
[appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'cmdwin native action'};
actionFound = 1;
end
% Check for editor menu action name
oldBindingIdx = find(strcmpi(macro, appdata.bindings(:,2)) & ...
strcmpi('editor menu action', appdata.bindings(:,4)));
appdata.bindings(oldBindingIdx,:) = []; %#ok clear any possible old binding
menuItemIdx = find(strcmpi(macro,appdata.edMenusMap(:,2)));
for menuIdx = 1 : length(menuItemIdx)
appdata.edMenusMap{menuItemIdx(menuIdx),1} = keystroke;
appdata.edMenusMap{menuItemIdx(menuIdx),3}.setAccelerator(jKeystroke);
[appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'editor menu action'};
actionFound = 1;
end
% Check for CW menu action name
oldBindingIdx = find(strcmpi(macro, appdata.bindings(:,2)) & ...
strcmpi('cmdwin menu action', appdata.bindings(:,4)));
appdata.bindings(oldBindingIdx,:) = []; %#ok clear any possible old binding
menuItemIdx = find(strcmpi(macro,appdata.cwMenusMap(:,2)));
for menuIdx = 1 : length(menuItemIdx)
appdata.cwMenusMap{menuItemIdx(menuIdx),1} = keystroke;
appdata.cwMenusMap{menuItemIdx(menuIdx),3}.setAccelerator(jKeystroke);
[appdata.bindings(end+1,:)] = {keystroke,macro,macroType,'cmdwin menu action'};
actionFound = 1;
end
% Bail out if native and/or menu action was handled
if actionFound
return;
end
end
% A non-native macro - Store the new/updated key-binding in the bindings list
[appdata.bindings(end+1,:)] = {keystroke,macro,macroType,macroClass};
end
catch
myError('YMA:EditorMacro:badMacro','bad MACRO or MACROTYPE input argument - read the help section');
end
%% Normalize the keystroke string to a standard format
function [keystroke,jKeystroke] = normalizeKeyStroke(keystroke)
try
if ~ischar(keystroke)
myError('YMA:EditorMacro:badKeystroke','bad KEYSTROKE input argument - must be a ''string''');
end
keystroke = strrep(keystroke,',',' '); % ',' => space (extra spaces are allowed)
keystroke = strrep(keystroke,'-',' '); % '-' => space (extra spaces are allowed)
keystroke = strrep(keystroke,'+',' '); % '+' => space (extra spaces are allowed)
[flippedKeyChar,flippedMods] = strtok(fliplr(keystroke));
keyChar = upper(fliplr(flippedKeyChar));
modifiers = lower(fliplr(flippedMods));
keystroke = sprintf('%s %s', modifiers, keyChar); % PRESSED: the character needs to be UPPERCASE, all modifiers lowercase
%keystroke = sprintf('%s typed %s', modifiers, keyChar); % TYPED: in runtime, the callback is for Typed, not Pressed
jKeystroke = javax.swing.KeyStroke.getKeyStroke(keystroke); % normalize & check format validity
keystroke = char(jKeystroke.toString); % javax.swing.KeyStroke => Matlab string
%keystroke = strrep(keystroke, 'pressed', 'released'); % in runtime, the callback is for Typed, not Pressed
%keystroke = strrep(keystroke, '-P', '-R'); % a different format in Matlab 6 (=Java 1.1.8)...
keystroke = strrep(keystroke,'keyCode ',''); % Fix for JVM 1.1.8 (Matlab 6)
if isempty(keystroke)
myError('YMA:EditorMacro:badKeystroke','bad KEYSTROKE input argument');
end
catch
myError('YMA:EditorMacro:badKeystroke','bad KEYSTROKE input argument - see help section');
end
%% Main keystroke callback function
function keyPressedCallback(jEditorPane,jEventData,jEditor,appdata,hEditorPane,varargin)
try
try
appdata = getappdata(jEditor,'EditorMacro');
catch
% gettappdata() might fail on Matlab 6 so it will fallback to the supplied appdata input arg
end
% Normalize keystroke string
try
keystroke = javax.swing.KeyStroke.getKeyStrokeForEvent(jEventData);
%get(jEventData)
catch
% Matlab 6 - for some reason, all Fn keys don't work with KeyReleasedCallback, but some of them work ok with KeyPressedCallback...
jEventData = get(jEditorPane,'KeyPressedCallbackData');
keystroke = javax.swing.KeyStroke.getKeyStroke(jEventData.keyCode, jEventData.modifiers);
keystroke = char(keystroke.toString); % no automatic type-casting in Matlab 6...
keystroke = strrep(keystroke,'keyCode ',''); % Fix for JVM 1.1.8 (Matlab 6)
jEditorPane = hEditorPane; % bypass Matlab 6 quirk...
end
% If this keystroke was bound to a macro
macroIdx = strmatch(keystroke,appdata.bindings(:,1),'exact');
if ~isempty(macroIdx)
% Disregard built-in actions - they are dispatched via a separate mechanism
userTextIdx = strcmp(appdata.bindings(macroIdx,4),'text');
userMacroIdx = strcmp(appdata.bindings(macroIdx,4),'user-defined macro');
if ~any(userTextIdx) & ~any(userMacroIdx) %#ok Matlab 6 compatibility
return;
end
% Dispatch the defined macro
macro = appdata.bindings{macroIdx,2};
macroType = appdata.bindings{macroIdx,3};
switch lower(macroType(1))
case 't' % Text
if ischar(macro)
% Simple string - insert as-is
elseif iscell(macro)
% Cell or cell array - feval this cell
macro = myFeval(macro{1}, jEditorPane, jEventData, macro{2:end});
else % assume @FunctionHandle
% feval this @FunctionHandle
macro = myFeval(macro, jEditorPane, jEventData);
end
% Now insert the resulting string into the jEditorPane caret position or replace selection
%caretPosition = jEditorPane.getCaretPosition;
try
% Matlab 7
%jEditorPane.insert(caretPosition, macro); % better to use replaceSelection() than insert()
try
% Try to dispatch on EDT
awtinvoke(jEditorPane, 'replaceSelection', macro);
catch
try
awtinvoke(java(jEditorPane), 'replaceSelection', macro);
catch
% no good - try direct invocation
jEditorPane.replaceSelection(macro);
end
end
catch
% Matlab 6
%jEditorPane.insert(macro, caretPosition); % note the reverse order of input args vs. Matlab 7...
try
% Try to dispatch on EDT
awtinvoke(jEditorPane, 'replaceRange', macro, jEditorPane.getSelStart, jEditorPane.getSelEnd);
catch
try
awtinvoke(java(jEditorPane), 'replaceRange', macro, jEditorPane.getSelStart, jEditorPane.getSelEnd);
catch
% no good - try direct invocation
jEditorPane.replaceRange(macro, jEditorPane.getSelStart, jEditorPane.getSelEnd);
end
end
end
case 'r' % Run
if ischar(macro)
% Simple string - evaluate in the base
evalin('base', macro);
elseif iscell(macro)
% Cell or cell array - feval this cell
myFeval(macro{1}, jEditorPane, jEventData, macro{2:end});
else % assume @FunctionHandle
% feval this @FunctionHandle
myFeval(macro, jEditorPane, jEventData);
end
end
end
catch
% never mind... - ignore error
%lasterr
try err = lasterror; catch, end %#ok for debugging, will fail on ML6
dummy=1; %#ok debugging point
end
%% Evaluate a function with exception handling to automatically fix too-many-inputs problems
function result = myFeval(func,varargin)
try
result = [];
if nargout
result = feval(func,varargin{:});
else
feval(func,varargin{:});
end
catch
% Try rerunning the function without the two default args
%v = version;
%if v(1)<='6'
% err.identifier = 'MATLAB:TooManyInputs'; %#ok no lasterror function so assume...
%else
% err = lasterror; %#ok
%end
%if strcmpi(err.identifier,'MATLAB:TooManyInputs')
if nargout
result = feval(func,varargin{3:end});
else
feval(func,varargin{3:end});
end
%end
end
%{
% TODO:
% =====
% - Handle Multi-KeyStroke bindings as in Alt-U U (Text / Uppercase)
% - Support native actions in EditorMacro(BINDINGSLIST) bulk mode of operation
% - Fix docking/menu limitations
% - GUI interface (list of actions, list of keybindings
%}
|
github
|
philippboehmsturm/antx-master
|
fuseimage.m
|
.m
|
antx-master/mritools/graphics/fuseimage.m
| 672 |
utf_8
|
a34594045b7c331ffa7fe079ecc44186
|
%Program Description
%This program is the main entry of the application.
%This program fuses/combines 2 images
%It supports both Gray & Color Images
%Alpha Factor can be varied to vary the proportion of mixing of each image.
%With Alpha Factor = 0.5, the two images mixed equally.
%With Alpha Facotr < 0.5, the contribution of background image will be more.
%With Alpha Facotr > 0.5, the contribution of foreground image will be more.
function fusedImg = fuseimage(bgImg, fgImg, alphaFactor)
bgImg = double(bgImg);
fgImg = double(fgImg);
fgImgAlpha = alphaFactor .* fgImg;
bgImgAlpha = (1 - alphaFactor) .* bgImg;
fusedImg = fgImgAlpha + bgImgAlpha;
|
github
|
philippboehmsturm/antx-master
|
gui_overlay.m
|
.m
|
antx-master/mritools/graphics/gui_overlay.m
| 5,716 |
utf_8
|
77759510b55c5d0c89e0648743440b30
|
function overlay_gui
hp=figure;
set(gcf,'color','w','units','normalized','tag','plot','menubar','none','toolbar','none');
ha=findobj(0,'tag','ant');
si=get(ha,'position');
siz=.15
set(hp,'position',[ si(1)-siz si(2) siz-.001 si(4)]);
h = uicontrol('style','pushbutton','units','norm', 'string','plot',...
'position',[0.1 0.9 .2 .05],'tag','tab1','callback', @plots);
% return
global an
pars={...
'file' 'x_t2.nii' 's'
% 'rfile' 'O:\harms1\harms3_lesionfill\templates\ANOpcol.nii' 's'
'rfile' fullfile(fileparts(an.datpath),'templates','ANOpcol.nii') 's'
'imswap' '1' 'd'
'doresize' '1' 'd'
'slice' '100' 'd'
'cmap' '' 's'
'alpha' '.5' 'd'
'nsb' '' 'd'
'cut' ['0 0 0 0'] 'd'
};
% F:\TOMsampleData\study4\templates
us.fs=9;
us.hp=hp;
us.pars=pars;
us.editable=[0 1];
us.position=[0 0 1 .9];
set(gcf,'userdata',us);
% t = uitable('Parent',hp,'Data',pars(:,1:2),'units','norm', 'position',[0 0 .9 .9],'ColumnEditable',logical([0 1]),'columnname','','rowname','');
% set(t,'ColumnWidth',{70 180});
% set(t,'fontsize',9);
% us.hp=hp;
% us.t=t;
% us.pars=pars;
%
% set(hp,'userdata',us);
set(gcf,'resizefcn',@maketable)
maketable
function maketable(he,ho)
us=get(gcf,'userdata');
if isfield(us ,'t')
data=us.t.Data;
t=us.t;
else
data=us.pars(:,1:2)
end
try;
delete(t);
end
% t=us.t
% pars=get(us.t.data)
% pars=us.t.Data;
% delete(us.t)
% t = uitable('Parent',us.hp,'Data',us.pars(:,1:2),'units','norm', ...
% 'position',[0 0 .9 .9],'ColumnEditable',logical([0 1]),'columnname','','rowname','',...
% 'columnwidth',{'auto','auto'});
%
% t = uitable('Parent',us.hp,'Data',us.pars(:,1:2),'units','norm')
%
%
% data=us.pars
dataSize = size(data);
% Create an array to store the max length of data for each column
maxLen = zeros(1,dataSize(2));
% Find out the max length of data for each column
% Iterate over each column
for i=1:dataSize(2)
for j=1:dataSize(1)% Iterate over each row
len = length(data{j,i});
if(len > maxLen(1,i))% Store in maxLen only if its the data is of max length
maxLen(1,i) = len;
end
end
end
% Some calibration needed as ColumnWidth is in pixels
cellMaxLen = num2cell(maxLen*7);
t = uitable('Parent',us.hp,'units','norm', 'position',us.position,...
'ColumnEditable', logical(us.editable),'columnname','','rowname','');
set(t,'fontsize',us.fs);
set(t, 'Data', data);
set(t,'units','pixels');
set(t, 'ColumnWidth', cellMaxLen(1:2));% Set ColumnWidth of UITABLE
set(t,'units','normalized');
us.t=t;
set(gcf,'userdata',us);
drawnow;
% pause(.5);
try
table = findjobj(us.t); %findjobj is in the file exchange
table1 = get(table,'Viewport');
jtable = get(table1,'View');
renderer = jtable.getCellRenderer(0,0);
renderer.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
renderer.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
% set(table,'HorizontalScrollBarPolicy',31)
end
%disable scrolling
try
jScrollPane = table.getComponent(0);
% catch
% us=get(gcf,'userdata');
% jTable = findjobj(us.t); % hTable is the handle to the uitable object
% jScrollPane = jTable.getComponent(0);
% javaObjectEDT(jScrollPane); % honestly not sure if this line matters at all
% currentViewPos = jScrollPane.getViewPosition; % save current position
% drawnow; % without this drawnow the following line appeared to do nothing
%
% end
javaObjectEDT(jScrollPane); % honestly not sure if this line matters at all
currentViewPos = jScrollPane.getViewPosition; % save current position
set(us.t,'CellSelectionCallback',{@mCellSelectionCallback,jScrollPane,currentViewPos});
end
function mCellSelectionCallback(e,r,jScrollPane,currentViewPos)
jScrollPane.setViewPosition(currentViewPos);
% us=get(gcf,'userdata');
% jTable = findjobj(us.t); % hTable is the handle to the uitable object
% jScrollPane = jTable.getComponent(0);
% javaObjectEDT(jScrollPane); % honestly not sure if this line matters at all
% currentViewPos = jScrollPane.getViewPosition; % save current position
% set(hTable,'data',newData); % resets the vertical scroll to the top of the table
% drawnow; % without this drawnow the following line appeared to do nothing
% jScrollPane.setViewPosition(currentViewPos);
% return
%% calback
function plots(hx,hy)
pl=(findobj(0,'tag','plot'));
if length(pl)>1
pl=pl(1);
end
us=get(pl,'userdata');
d=get(us.t,'data');
fmt=us.pars(:,3);
s=cell2struct(d(:,2)',d(:,1)',2);
if strcmp(s.nsb,'line')==0; s.nsb=str2num(s.nsb); end
s.imswap=str2num(s.imswap);
s.alpha=str2num(s.alpha);
s.cut=str2num(s.cut);
if isempty(strfind(s.slice,'''')) ; s.slice=str2num(s.slice); end
warp_summary2(s);
|
github
|
philippboehmsturm/antx-master
|
mousebutton.m
|
.m
|
antx-master/mritools/graphics/mousebutton.m
| 1,956 |
utf_8
|
1e712ffcef0edff4612c8c034d06cc0e
|
%% define mousebutton [left/right, double-left/right,& SHIFT-CONTROL-ALT ]
%% button:
% 1:left
% 2:right
% 3:double click left
% 4:double click right
%% sca:
% 3-element vector refers to combinations of SHIFT-CONTROL-ALT
%% button & sca can be combined
%EXAMPLE:
% [b sca] = mousebutton;
% if b==0; return; end %necessary to allow double-click
function [button sca]=mousebutton
persistent chkx
persistent chkxtype
persistent chkbutton
persistent chkdouble
button = 0;
sca = [];
val=0;
if isempty(chkx)
chkxtype=get(gcf,'SelectionType');
chkdouble=1;
chkx = 1;
pause(0.3); %Add a delay to distinguish single click from a double click
if chkx == 1
%% SINGLE-CLICK
val=0;
chkx = [];
chkdouble=0;
% disp('single-click');
[button sca]=getbutton(0,chkxtype);
% disp(button);
end
else
%% DOUBLE-CLICK
chkx = [];
%
% disp('double-click');
[buttonx scax]=getbutton(2,chkxtype);
val=1;
chkbutton=[buttonx scax];
button=0;
sca=[0 0 0];
chkdouble=chkdouble+1;
end
if ~isempty(chkbutton) && chkdouble==2
button=chkbutton(1);
sca =chkbutton(2:end);
chkdouble=0;
end
function [button sca]=getbutton(nclick,chkxtype)
% chkxtype
% button='';
% pause(.2)
% return
% mouse_seltype=get(gcf,'SelectionType')
if strcmp(chkxtype,'normal') %LEFT
button=1+nclick;
elseif strcmp(chkxtype,'alt') %RIGHT
button=2+nclick;
elseif strcmp(chkxtype,'extend')
if nclick==2; nclick=1 ; end
button=5+nclick;
else
% button=10+nclick
button = 0;
sca = [];
end
modifiers = get(gcf,'CurrentModifier');
s = ismember('shift', modifiers); % true/false
c = ismember('control', modifiers); % true/false
a = ismember('alt', modifiers); % true/false
sca=[s c a];
|
github
|
philippboehmsturm/antx-master
|
montage_t2image.m
|
.m
|
antx-master/mritools/graphics/montage_t2image.m
| 2,138 |
utf_8
|
bab38dc29fb50bab0ca82943d9b9b801
|
function montage_t2image
file='t2.nii';
fil=antcb('getsubjects');
fis=stradd(fil,[filesep file],2);
d=[];
for i=1:size(fis,1)
[ha a]=rgetnii(fis{i});
% [xyz xyzmm]=getcenter(ha);
xyzmm=[0 0 0];
[xyz u]=voxcalc(xyzmm,ha,'mm2idx');
d0=double(rot90(squeeze(a(:,:,xyz(3)))));
if i==1
sir=size(d0);
end
d0=d0-min(d0(:));
d0=(d0./max(d0(:)));
si=size(d0);
if all([si==sir])==0
d0= imresize(d0,si);
end
d(:,:,i)=d0;
end
f=montageout(permute(d,[1 2 4 3]));
% fg,imagesc((f)); colormap gray
sif=size(f);
nb=size(f)./sir;
do=fliplr(round(linspace(1,sif(1)-sir(1),nb(1))))+10;%round(sir(1)/10);
re=round(linspace(1,sif(2)-sir(2),nb(2)));
co=[repmat(re(:),[nb(1) 1]) sort(repmat(do(:),[nb(2) 1]),'ascend')];
fg;imagesc((f)); colormap(gray);
pas=replacefilepath(fil,'');
for i=1:size(fis,1)
if rem(i,2)==0; adj=20; else; adj=0;end
hp=text(co(i,1),co(i,2)+adj,pas{i},'tag','txt','fontsize',4,'color','w','interpreter','none' ,...
'ButtonDownFcn',['explorer(' '''' fil{i} '''' ')'] );
end
% delete(findobj(gcf,'tag','txt'))
us.sif=sif;
us.nb =nb;
us.sir=sir;
us.pas=pas;
us.fil=fil;
us.fis=fis;
set(gcf,'userdata',us);
set(findobj(gcf,'type','image'),'ButtonDownFcn',@showinfo);
set(gcf,'name',['click <mouse name> to open folder; click on image to view mouse-specific headerInformation']);
axis off
hlin=sir(1):sir(1):sif(1)-sir(1);
for i=1:length(hlin); hline(hlin(i),'color',[.1 .1 .1]); end
vlin=sir(2):sir(2):sif(2)-sir(2);
for i=1:length(vlin); vline(vlin(i),'color',[.1 .1 .1]); end
set(gcf,'color','k')
%% calback
function showinfo(he,ho)
us=get(gcf,'userdata');
cp=round(get(gca,'CurrentPoint'));
cp=cp(1,1:2);ns=[floor(cp(2)/us.sir(1)+1) floor(cp(1)/us.sir(2)+1)];
id=ns(1)*us.nb(2)-us.nb(2)+ns(2);
hb=spm_vol(us.fis(id)); hb=hb{1};
li=struct2list(hb);
disp('______________________________________________________________________')
disp(char(li));
% title(li,'fontsize',4,'HorizontalAlignment','left');
|
github
|
philippboehmsturm/antx-master
|
axslider.m
|
.m
|
antx-master/mritools/graphics/axslider.m
| 4,823 |
utf_8
|
0885347d140702fb5688f9dc28e21966
|
function ax=axslider(nb,varargin)
warning off;
if nargin>1
%vnew=varargin{1};
vara=reshape(varargin,[2 length(varargin)/2])';
vnew=cell2struct(vara(:,2)',vara(:,1)',2);
else
vnew=struct();
end
v=vnew;
% n=20;
% nr=3;
n=nb(1);
nr=nb(2);
if n<nr
norig=n;
n=nr;
removeimg=1;
else
removeimg=0;
end
% ax=[];
% for i=1:n*nr
% ax(i,1)=subplot(20,3,i); plot(1:10);title(i);
% end
%
% p=cell2mat(get(ax,'position'))
nps=nr;
slidwid=.02;
lewid =.01;
% sub=(1/nps)*.8;
up=0:1/nps:1-1/nps;
wid=(1-(slidwid+lewid))/nr;
re=[0:wid:wid*(nr-1)] ;
si=1/nps;
hi=si;
hit=cumsum(repmat(hi,[n 1]));
hit=flipud(hit-hit(end-(nps-1)));
si2=wid;
% si2=si*1.00
shift2right=(si-si2);
p=[];
for i=1:length(re)
p0=[repmat(re(i),[size(hit,1) 1]) hit repmat(si2,[size(hit,1) 2])];
p=[p;p0];
end
p=sortrows(p,[ -2 1]);
p(:,1)=p(:,1)+shift2right*.75;
if removeimg==1;
nkeep=norig.*nr;
p=p(1:nkeep,:);
end
figure('color','w','units','norm');
u=uicontrol('style','slider','units','normalized');
set(u,'position',[1-slidwid 0 slidwid 1]);
set(u,'value',get(u,'max'),'tag','slid');
set(gcf,'WindowKeyPressFcn',@key);
for i=1:size(p,1)
ax(i,1)= axes('Position',p(i,:),'tag','ax');
% text(.5,.5,num2str(i));
end
% ax=findobj(gcf,'tag','ax');
% p2=cell2mat(get(ax,'position'));
stp=-.1;
% p2(:,2)=p2(:,2)+stp;
% for i=1:length(ax)
% set(ax(i),'position',p2(i,:));
% end
%% num
if isfield(v,'num')==0
stepimg=nb(2);
else
stepimg=1;
end
ip=1:stepimg:prod(nb);
si=0.03;
for i=1:length(ip)
ref=p(ip(i),:);
if stepimg==1
bpos(i,:)=[ref(1) ref(2)+ref(4)-si si si];
else
bpos(i,:)=[0 ref(2)+ref(4)-si si si];
end
b(i)=uicontrol('style','text','units','norm','position',bpos(i,:),'string',num2str(i),...
'backgroundcolor','k','foregroundcolor','w');
end
%% checkbox
if isfield(v,'checkbox')
chk.ichk=1:1:prod(nb);
si=0.03;
for i=1:length(chk.ichk)
ref=p(chk.ichk(i),:);
chk.pos(i,:)=[ref(1)+si ref(2)+ref(4)-si si si];
chk.hchk(i)=uicontrol('style','checkbox','units','norm','position',chk.pos(i,:),'string',num2str(i),...
'backgroundcolor','k','foregroundcolor','w','value',0,'userdata', (i),'tag','chk1');
end
end
us=[];
us.v=v;
us.ax=ax;
us.stp=stp;
us.p=p;
us.up=up;
us.num =b;%number + ip
us.numip=ip;
us.numpos=bpos;
if isfield(v,'checkbox')
us.chk=chk;
end
set(u,'userdata',us);
set(u,'callback',{@slidupdate});
set(findobj(gcf,'type','axes'),'XTickLabel','','YTickLabel','');
set(gcf,'WindowScrollWheelFcn',@sliderupdate)
function key(h,e)
stp=.05;
if strcmp(e.Key,'downarrow')
u=findobj(gcf,'tag','slid');
v=get(u,'value');
v=v-stp;
if v<0; v=0; end
set(u,'value',v);
slidupdate;
elseif strcmp(e.Key,'uparrow')
u=findobj(gcf,'tag','slid');
v=get(u,'value');
v=v+stp;
if v>1; v=1; end
set(u,'value',v);
slidupdate;
end
stp=.2;
if strcmp(e.Key,'rightarrow')
u=findobj(gcf,'tag','slid');
v=get(u,'value');
v=v-stp;
if v<0; v=0; end
set(u,'value',v);
slidupdate;
elseif strcmp(e.Key,'leftarrow')
u=findobj(gcf,'tag','slid');
v=get(u,'value');
v=v+stp;
if v>1; v=1; end
set(u,'value',v);
slidupdate;
end
%% callback
function sliderupdate(hf,e)
sign(e.VerticalScrollCount);
u=findobj(gcf,'tag','slid');
% stp=get(u,'SliderStep');
stp=[.1 .2];
nval=get(u,'value')+stp(2).*-sign(e.VerticalScrollCount);
if nval>1; nval=1; end
if nval<0; nval=0; end
set(u,'value',nval);
slidupdate([],[])
function slidupdate(u,e)
u=findobj(gcf,'tag','slid');
us=get(u,'userdata');
ax=us.ax;
p=us.p;
axvis=ax;
for i=1:length(axvis)
set(get(axvis(i),'children'),'visible','off');
end
val=1-get(u,'value');
yr=[min(p(:,2)) max(p(:,2))];
stp=abs(min(yr)*val);
if val==0
stp=stp-.05;
elseif val==1
stp=stp+.05;
end
p2=p;
p2(:,2)=p2(:,2)+stp;
for i=1:length(ax)
set(ax(i),'position',p2(i,:));
end
%% number
nu=us.num;
p3=us.numpos;
p3(:,2)=p3(:,2)+stp;
for i=1:length(nu)
set(nu(i),'position',p3(i,:));
end
%% checkbox
if isfield(us,'chk')
hh=us.chk.hchk;
p3=us.chk.pos;
p3(:,2)=p3(:,2)+stp;
for i=1:length(hh)
set(hh(i),'position',p3(i,:));
end
end
axvis=ax(find(p2(:,2)>-1 & p2(:,2)<1));
for i=1:length(axvis)
set(get(axvis(i),'children'),'visible','on');
end
% p=us.p
% ax=us.ax
% p2=cell2mat(get(ax,'position'));
% stp=-.1;
% p2(:,2)=p2(:,2)+stp;
% for i=1:length(ax)
% set(ax(i),'position',p2(i,:));
% end
|
github
|
philippboehmsturm/antx-master
|
montageout.m
|
.m
|
antx-master/mritools/graphics/montageout.m
| 13,006 |
utf_8
|
a692deab49bd51f1bd7dcc6685cd7274
|
function h = montage(varargin)
%MONTAGE Display multiple image frames as rectangular montage.
% MONTAGE(FILENAMES) displays a montage of the images specified in
% FILENAMES. FILENAMES is an N-by-1 or 1-by-N cell array of file name
% strings. If the files are not in the current directory or in a
% directory on the MATLAB path, specify the full pathname. (See the
% IMREAD command for more information.) If one or more of the image files
% contains an indexed image, MONTAGE uses the colormap from the first
% indexed image file.
%
% By default, MONTAGE arranges the images so that they roughly form a
% square, but you can specify other arrangements using the 'Size'
% parameter (see below). MONTAGE creates a single image object to
% display the images.
%
% MONTAGE(I) displays a montage of all the frames of a multiframe image
% array I. I can be a sequence of binary, grayscale, or truecolor images.
% A binary or grayscale image sequence must be an M-by-N-by-1-by-K array.
% A truecolor image sequence must be an M-by-N-by-3-by-K array.
%
% MONTAGE(X,MAP) displays all the frames of the indexed image array X,
% using the colormap MAP for all frames. X is an M-by-N-by-1-by-K array.
%
% MONTAGE(..., PARAM1, VALUE1, PARAM2, VALUE2, ...) returns a customized
% display of an image montage, depending on the values of the optional
% parameter/value pairs. See Parameters below. Parameter names can be
% abbreviated, and case does not matter.
%
% H = MONTAGE(...) returns the handle of the single image object which
% contains all the frames displayed.
%
% Parameters
% ----------
% 'Size' A 2-element vector, [NROWS NCOLS], specifying the number
% of rows and columns in the montage. Use NaNs to have
% MONTAGE calculate the size in a particular dimension in
% a way that includes all the images in the montage. For
% example, if 'Size' is [2 NaN], MONTAGE creates a montage
% with 2 rows and the number of columns necessary to
% include all of the images. MONTAGE displays the images
% horizontally across columns.
%
% Default: MONTAGE calculates the rows and columns so the
% images in the montage roughly form a square.
%
% 'Indices' A numeric array that specifies which frames MONTAGE
% includes in the montage. MONTAGE interprets the values
% as indices into array I or cell array FILENAMES. For
% example, to create a montage of the first four frames in
% I, use this syntax:
%
% montage(I,'Indices',1:4);
%
% Default: 1:K, where K is the total number of frames or
% image files.
%
% 'DisplayRange' A 1-by-2 vector, [LOW HIGH], that adjusts the display
% range of the images in the image array. The images
% must be grayscale images. The value LOW (and any value
% less than LOW) displays as black, the value HIGH (and
% any value greater than HIGH) displays as white. If you
% specify an empty matrix ([]), MONTAGE uses the minimum
% and maximum values of the images to be displayed in the
% montage as specified by 'Indices'. For example, if
% 'Indices' is 1:K and the 'Display Range' is set to [],
% MONTAGE displays the minimum value in of the image array
% (min(I(:)) as black, and displays the maximum value
% (max(I(:)) as white.
%
% Default: Range of the datatype of the image array.
%
% Class Support
% -------------
% A grayscale image array can be uint8, logical, uint16, int16, single,
% or double. An indexed image array can be logical, uint8, uint16,
% single, or double. MAP must be double. A truecolor image array can
% be uint8, uint16, single, or double. The output is a handle to the
% image object produced by MONTAGE.
%
% Example 1
% ---------
% This example creates a montage from a series of images in ten files.
% The montage has two rows and five columns. Use the DisplayRange
% parameter to highlight structures in the image.
%
% fileFolder = fullfile(matlabroot,'toolbox','images','imdemos');
% dirOutput = dir(fullfile(fileFolder,'AT3_1m4_*.tif'));
% fileNames = {dirOutput.name}'
% montage(fileNames, 'Size', [2 5]);
%
% figure, montage(fileNames, 'Size', [2 5], ...
% 'DisplayRange', [75 200]);
%
% Example 2
% ---------
% This example shows you how to customize the number of images in the
% montage.
%
% % Create a default montage.
% load mri
% montage(D, map)
%
% % Create a new montage containing only the first 9 images.
% figure
% montage(D, map, 'Indices', 1:9);
%
% See also IMMOVIE, IMSHOW, IMPLAY.
% Copyright 1993-2008 The MathWorks, Inc.
% $Revision: 1.1.8.10 $ $Date: 2009/09/28 20:24:34 $
warning off;
[I,cmap,mSize,indices,displayRange] = parse_inputs(varargin{:});
if isempty(indices) || isempty(I)
hh = imshow([]);
if nargout > 0
h = hh;
end
return;
end
% Function Scope
nFrames = numel(indices);
nRows = size(I,1);
nCols = size(I,2);
montageSize = calculateMontageSize(mSize);
bigImage = createMontageImage;
if isempty(cmap)
if isempty(displayRange)
num = numel(I(:,:,:,indices));
displayRange(1) = min(reshape(I(:,:,:,indices),[1 num]));
displayRange(2) = max(reshape(I(:,:,:,indices),[1 num]));
end
% hh = imshow(bigImage, displayRange);
else
% hh = imshow(bigImage,cmap);
end
h=bigImage;
% if nargout > 0
% h = hh;
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function montageSize = calculateMontageSize(mSize)
if isempty(mSize) || all(isnan(mSize))
%Calculate montageSize for the user
% Estimate nMontageColumns and nMontageRows given the desired
% ratio of Columns to Rows to be one (square montage).
aspectRatio = 1;
montageCols = sqrt(aspectRatio * nRows * nFrames / nCols);
% Make sure montage rows and columns are integers. The order in
% the adjustment matters because the montage image is created
% horizontally across columns.
montageCols = ceil(montageCols);
montageRows = ceil(nFrames / montageCols);
montageSize = [montageRows montageCols];
elseif any(isnan(mSize))
montageSize = mSize;
nanIdx = isnan(mSize);
montageSize(nanIdx) = ceil(nFrames / mSize(~nanIdx));
elseif prod(mSize) < nFrames
eid = sprintf('Images:%s:sizeTooSmall', mfilename);
error(eid, ...
'SIZE must be big enough to include all frames in I.');
else
montageSize = mSize;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function b = createMontageImage
nMontageRows = montageSize(1);
nMontageCols = montageSize(2);
nBands = size(I, 3);
sizeOfBigImage = [nMontageRows*nRows nMontageCols*nCols nBands 1];
if islogical(I)
b = false(sizeOfBigImage);
else
b = zeros(sizeOfBigImage, class(I));
end
rows = 1 : nRows;
cols = 1 : nCols;
k = 1;
for i = 0 : nMontageRows-1
for j = 0 : nMontageCols-1,
if k <= nFrames
b(rows + i * nRows, cols + j * nCols, :) = ...
I(:,:,:,indices(k));
else
return;
end
k = k + 1;
end
end
end
end %MONTAGE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I,cmap,montageSize,idxs,displayRange] = parse_inputs(varargin)
iptchecknargin(1, 8, nargin, mfilename);
% initialize variables
cmap = [];
montageSize = [];
charStart = find(cellfun('isclass', varargin, 'char'));
if iscell(varargin{1})
%MONTAGE(FILENAMES.,..)
[I,cmap] = getImagesFromFiles(varargin{1});
else
%MONTAGE(I,...) or MONTAGE(X,MAP,...)
I = varargin{1};
iptcheckinput(varargin{1}, ...
{'uint8' 'double' 'uint16' 'logical' 'single' 'int16'}, {}, ...
mfilename, 'I, BW, or RGB', 1);
end
nframes = size(I,4);
displayRange = getrangefromclass(I);
idxs = 1:nframes;
if isempty(charStart)
%MONTAGE(FILENAMES), MONTAGE(I) or MONTAGE(X,MAP)
if nargin == 2
%MONTAGE(X,MAP)
cmap = validateColormapSyntax(I,varargin{2});
end
return;
end
charStart = charStart(1);
if charStart == 3
%MONTAGE(X,MAP,Param1,Value1,...)
cmap = validateColormapSyntax(I,varargin{2});
end
paramStrings = {'Size', 'Indices', 'DisplayRange'};
for k = charStart:2:nargin
param = lower(varargin{k});
inputStr = iptcheckstrs(param, paramStrings, mfilename, 'PARAM', k);
valueIdx = k + 1;
if valueIdx > nargin
eid = sprintf('Images:%s:missingParameterValue', mfilename);
error(eid, ...
'Parameter ''%s'' must be followed by a value.', ...
inputStr);
end
switch (inputStr)
case 'Size'
montageSize = varargin{valueIdx};
iptcheckinput(montageSize,{'numeric'},...
{'vector','positive'}, ...
mfilename, 'Size', valueIdx);
if numel(montageSize) ~= 2
eid = sprintf('Images:%s:invalidSize',mfilename);
error(eid, 'Size must be a 2-element vector.');
end
montageSize = double(montageSize);
case 'Indices'
idxs = varargin{valueIdx};
iptcheckinput(idxs, {'numeric'},...
{'vector','integer','nonnan'}, ...
mfilename, 'Indices', valueIdx);
invalidIdxs = ~isempty(idxs) && ...
any(idxs < 1) || ...
any(idxs > nframes);
if invalidIdxs
eid = sprintf('Images:%s:invalidIndices',mfilename);
error(eid, ...
'An index in INDICES cannot be less than 1 %s', ...
'or greater than the number of frames in I.');
end
idxs = double(idxs);
case 'DisplayRange'
displayRange = varargin{valueIdx};
displayRange = checkDisplayRange(displayRange, mfilename);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cmap = validateColormapSyntax(I,cmap)
if isa(I,'int16')
eid = sprintf('Images:%s:invalidIndexedImage',mfilename);
error(eid, 'An indexed image can be uint8, uint16, %s', ...
'double, single, or logical.');
end
iptcheckinput(cmap,{'double'},{},mfilename,'MAP',1);
if size(cmap,1) == 1 && prod(cmap) == numel(I)
% MONTAGE(D,[M N P]) OBSOLETE
eid = sprintf('Images:%s:obsoleteSyntax',mfilename);
error(eid, ...
'MONTAGE(D,[M N P]) is an obsolete syntax.\n%s', ...
'Use multidimensional arrays to represent multiframe images.');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I, map] = getImagesFromFiles(fileNames)
if isempty(fileNames)
eid = sprintf('Images:%s:invalidType', mfilename);
msg = 'FILENAMES must be a cell array of strings.';
error(eid, msg);
end
nframes = length(fileNames);
[img, map] = getImageFromFile(fileNames{1}, mfilename);
classImg = class(img);
sizeImg = size(img);
if length(sizeImg) > 2 && sizeImg(3) == 3
nbands = 3;
else
nbands = 1;
end
sizeImageArray = [sizeImg(1) sizeImg(2) nbands nframes];
if islogical(img)
I = false(sizeImageArray);
else
I = zeros(sizeImageArray, classImg);
end
I(:,:,:,1) = img;
for k = 2 : nframes
[img,tempmap] = getImageFromFile(fileNames{k}, mfilename);
if ~isequal(size(img),sizeImg)
eid = sprintf('Images:%s:imagesNotSameSize', mfilename);
error(eid, ...
'FILENAMES must contain images that are the same size.');
end
if ~strcmp(class(img),classImg)
eid = sprintf('Images:%s:imagesNotSameClass', mfilename);
error(eid, ...
'FILENAMES must contain images that have the same class.');
end
if isempty(map) && ~isempty(tempmap)
map = tempmap;
end
I(:,:,:,k) = img;
end
end
|
github
|
philippboehmsturm/antx-master
|
seemore.m
|
.m
|
antx-master/mritools/graphics/seemore.m
| 5,290 |
utf_8
|
8cf3d7906045acf920d73e5aed74ddc6
|
function seemore(varargin)
% SEEMORE displays the content of the last statement in the history
% with clicklable links that allows users to interactively expand
% subcomponents of structured data.
%
% SEEMORE VARIABLE displays the content of the variable.
%
% This tool is usefull to anyone who works with the structured data
% types, i.e. MATLAB's struct() command. It provides an improved
% display on the MATLAB console screen and is more clearly laid out
% than the built-in variable viewer.
%
% Example:
% X=struct('a',struct('aa',1,'ab',2),'b',struct('ba',3,'bb',4))
% seemore X
% determine variable to be displayed
if nargin<1
name= 'ans';
history= com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory;
lastcmd= length(history);
while lastcmd>1 && history(lastcmd).startsWith('seemore')
lastcmd = lastcmd-1;
end
if lastcmd>1
history= char(history(lastcmd));
if ~isempty(find(history=='=',1))
history= history(1:find(history=='=',1)-1);
end
if isvarname(history)
name= history;
end
end
if strcmp('ans',name) && isempty(evalin('base','who(''ans'')'))
error('See more of what?');
end
else
name= varargin{1};
end
% print the header for the inspected variable
fprintf('\n');
if ischar(name)
% simply print the name
fprintf('%s',name);
try
obj= evalin('base', ['{',name,'}']);
catch e
error('Command can not be evaluated: %s', name);
end
name={name};
else
% print the sequence of hierarchical fields
for i=1:length(name)
if i==1
fprintf('%s',name{i});
obj= {evalin('base', name{i})};
else
if isnumeric(name{i})
obj= {obj{name{i}}};
fprintf('(%d)',name{i});
elseif strcmp(name{i},'*')
% convert a array of structs into cells
newobj= cell(1,prod(size(obj{1})));
for j=1:length(newobj)
newobj{j}= obj{1}(j);
end
obj= newobj;
else
obj={obj{1}.(name{i})};
fprintf('.%s',name{i});
end
end
end
fprintf('')
end
if length(obj)==1 && isstruct(obj{1}) && length(obj{1})>1
fprintf('= <a href="matlab:seemore(%s)"><%d elements></a>\n', ...
cell2str({name{:},'*'}), prod(size(obj{1})));
else
fprintf(' =\n');
end
if length(obj)>1
% object value is a sequence
for i=1:prod(size(obj))
fprintf('%5d : %s\n', i, getLink({obj{i}}, i, name));
end
else
% Value is a simple
obj= obj{1};
if isstruct(obj)
fields= fieldnames(obj);
% find the indentation length
indent= 4;
for i=1:length(fields)
field= fields{i};
indent= max(4+length(field), indent);
end
% print all struct fields
for i=1:length(fields)
field= fields{i};
value= {obj.(field)};
fprintf('%s%s: %s\n', ...
char(ones(1,indent-length(field))*' '), field, ...
getLink(value, field, name));
end
elseif ischar(obj)
fprintf(' %s\n', obj);
else
disp(obj);
end
end
end
% generate a link with a short description
function nest= getLink(value, field, name)
% build the output line for a struct field
if length(value)==1
[nest,islink] =shortform(value{1});
else
nest= ['<',mat2str(length(value)), ' elements>'];
islink= true;
end
% present a string or a link
if islink
nest= sprintf('<a href="matlab:seemore(%s)">%s</a>',...
cell2str({name{:},field}), nest);
end
end
% generate a short form of the viewed variable
function [value,link]= shortform(value)
link= true;
if ischar(value)
link= length(value)>80;
elseif isnumeric(value)
if sum(size(value))<10
value= mat2str(value);
link= false;
end
elseif islogical(value) && length(value)==1
if value
value='true';
else
value='false';
end
link= false;
end
if link
% object can be expanded on click
post='';
if isstruct(value)
post=[' with ',mat2str(length(fieldnames(value))),' fields'];
end
% format dimensions (e.g. 10x10)
dim= size(value);
link= prod(dim)>0;
dimstr= '';
for i=1:length(dim);
if i>1
dimstr= strcat(dimstr,'x');
end
dimstr= [dimstr, mat2str(dim(i))];
end
% format final
type= class(value);
value= ['[',dimstr,' ',type,post,']'];
end
end
% format a cell into a Matlab source string
function str= cell2str(value)
str='{';
for i=1:length(value)
if i>1
str= strcat(str,',');
end
str= strcat(str, mat2str(value{i}));
end
str= strcat(str,'}');
end
|
github
|
philippboehmsturm/antx-master
|
antpath.m
|
.m
|
antx-master/mritools/ant/antpath.m
| 604 |
utf_8
|
4289c9ecc3d1ab28be1283ab66e0ad35
|
%% get path and struct with FPlinks to ANT and TPMs in refspace
% [pathx s]=antpath
function [pathx s]=antpath(arg)
pathx=fileparts(mfilename('fullpath'));
s.refpa=fullfile(pathx, 'templateBerlin_hres');
s.refTPM={...
fullfile(s.refpa,'_b1grey.nii')
fullfile(s.refpa,'_b2white.nii')
fullfile(s.refpa,'_b3csf.nii')
};
s.ano=fullfile(s.refpa,'ANO.nii');
s.avg =fullfile(s.refpa,'AVGT.nii');
s.fib =fullfile(s.refpa,'FIBT.nii');
s.refsample= fullfile(s.refpa,'_sample.nii');
s.gwc =fullfile(s.refpa,'GWC.nii');
if exist('arg')
explorer(pathx);
end
|
github
|
philippboehmsturm/antx-master
|
antconfig.m
|
.m
|
antx-master/mritools/ant/antconfig.m
| 5,268 |
utf_8
|
c306639220f1d91c671c8adfeb870dab
|
function varargout=antconfig(showgui,varargin)
% varargin : with parameter-pairs
% currently:
% 'parameter' 'default' ...load default parameter (i.e. overrides global "an" struct )
% otherwise use an struct
% 'savecb' 'yes'/'no' ...show save checkbox, default is 'yes'
% antconfig(1,'parameter','default','savecb','no')
% antconfig(1,'parameter','default')
% antconfig(1)
if exist('showgui')~=1 ; showgui=1; end
%% additional parameters
para=struct();
if ~isempty(varargin)
para=cell2struct(varargin(2:2:end),varargin(1:2:end),2);
end
if isfield(para,'parameter') && strcmp(getfield(para,'parameter'),'default') ==1
an=struct();
else
global an
end
[pant r]= antpath;
p={...
'inf99' '*** CONFIGURATION PARAMETERS *** ' '' ''
'inf100' '===================================' '' ''
'inf1' '% DEFAULTS ' '' ''
'project' 'NEW PROJECT' 'PROJECTNAME OF THE STUDY (arbitrary tag)' ''
'datpath' '<MANDATORY TO FILL>' 'studie''s datapath, MUST BE be specified, and named "dat", such as "c:\b\study1\dat" ' 'd'
'voxsize' [.07 .07 .07] 'voxelSize (default is [.07 .07 .07])' cellfun(@(a) {repmat(a,1,3)}, {' .01' ' .03' ' .05' ' .07'}')
'inf2' '% WARPING ' '' ''
'wa.refTPM' r.refTPM 'c1/c2/c3-compartiments (reference)' ,'mf'
'wa.ano' r.ano 'reference anotation-image' 'f'
'wa.avg' r.avg 'reference structural image' 'f'
'wa.fib' r.fib 'reference fiber image' 'f'
'wa.refsample' r.refsample 'a sample image in reference space' 'f'
'wa.create_gwc' 1 'create overlay gray-white-csf-image (recommended for visualization) ' 'b'
'wa.create_anopcol' 1 'create pseudocolor anotation file (recommended for visualization) ' 'b'
'wa.cleanup' 1 'delete unused files in folder' 'b'
'wa.usePCT' 2 'use Parallel Computing toolbox (0:no/1:SPMD/2:parfor) ' {1,2,3}
'wa.usePriorskullstrip' 1 'use a priori skullstripping' 'b'
% 'wa.autoreg' 1 'automatic registration (0:manual, 1:automatic)' 'b'
'wa.elxParamfile' {...
which('Par0025affine.txt');
which('Par0033bspline_EM2.txt')} 'ELASTIX Parameterfile' 'mf'
'wa.elxMaskApproach' 1 'currently the only approach available (will be more soon)' ''
'wa.tf_ano' 1 'create "ix_ANO.nii" (template-label-image) in MOUSESPACE (inverseTrafo)' 'b'
'wa.tf_anopcol' 1 'create "ix_ANOpcol.nii" (template-pseudocolor-label-image label) in MOUSESPACE (inverseTrafo)' 'b'
'wa.tf_avg' 1 'create "ix_AVGT.nii" (template-structural-image) in MOUSESPACE (inverseTrafo)' 'b'
'wa.tf_refc1' 1 'create "ix_refIMG.nii" (template-grayMatter-image) in MOUSESPACE (inverseTrafo)' 'b'
'wa.tf_t2' 1 'create "x_t2.nii" (mouse-t2-image) in TEMPLATESPACE (forwardTrafo)' 'b'
'wa.tf_c1' 1 'create "x_c1t2.nii" (mouse-grayMatter-image) in TEMPLATESPACE (forwardTrafo)' 'b'
'wa.tf_c2' 1 'create "x_c2t2.nii" (mouse-whiteMatter-image) in TEMPLATESPACE (forwardTrafo)' 'b'
'wa.tf_c3' 1 'create "x_c3t2.nii" (mouse-CSF-image) in TEMPLATESPACE (forwardTrafo)' 'b'
'wa.tf_c1c2mask' 1 'create "x_c1c2mask.nii" (mouse-gray+whiteMatterMask-image) in TEMPLATESPACE (forwardTrafo)' 'b'
};
p2=paramadd(p,an);%add/replace parameter
if showgui==1
if isfield(para,'savecb') && strcmp(getfield(para,'savecb'),'no') ==1
cb1string='';
else
cb1string='save settings as studie''s confogfile';
end
% [m z a params]=paramgui(p2,'uiwait',1,'close',1,'editorpos',[.03 0 1 1],'figpos',[.2 .3 .6 .5 ],...
% 'title','SETTINGS','pb1string','OK','cb1string','save settings as studie''s confogfile');
figpos=[0.1688 0.3000 0.8073 0.6111];
[m z a params]=paramgui(p2,'uiwait',1,'close',1,'editorpos',[.03 0 1 1],'figpos',figpos,...
'title','SETTINGS','pb1string','OK','cb1string',cb1string);
if params.cb1==1
[fi, pa] = uiputfile(fullfile(pwd,'*.m'), 'save as configfile (example "project_study1")');
if pa~=0
pwrite2file(fullfile(pa,fi),m);
end
end
else
z=[];
for i=1:size(p2,1)
eval(['z.' p2{i,1} '=' 'p2{' num2str(i) ',2};']);
end
end
%% aditional variables
z.templatepath=fullfile(fileparts(z.datpath),'templates');
z.ls=struct2list(z);
try;
z.mdirs=an.mdirs ;
end
an=z;
%set Listbox-2
ls=an.ls;
ls(regexpi2(ls,'^\s*z.inf\d'))=[];
ls(regexpi2(ls,'^\s*z.mdirs'))=[];
ls=regexprep(ls,'^\s*z.','');
set(findobj(findobj('tag','ant'),'tag','lb2'),'string',ls);
try
varargout{1}=m;
end
try
varargout{2}=z;
end
try
varargout{3}=a;
end
try
varargout{4}=params;
end
|
github
|
philippboehmsturm/antx-master
|
showfun.m
|
.m
|
antx-master/mritools/ant/showfun.m
| 2,089 |
utf_8
|
67c71a1a9c54a9cb7737c1fb5fc0d1a8
|
%% #b displays the main functions of the [ANT]-toolbox with hyperlinks for HELP and EDIT-MODE
% click on the function-name in the command-window to show the function's help
% click on the [ed]-hyperlink to open this function
function showfun
f={ 'ant'
'antcb'
'antfun'
'ante'
'antsettings'
'antver'
'xcopyrenameexpand'
'xcoreg'
'xwarp3'
'xbruker2nifti'
'paramgui'
'showfun'
'xoverlay'
'xdeform2'
'xdeformpop'
'xexport'
'xgenerateJacobian'
'xgetlabels3'
'xnewproject'
'xmaskgenerator'
'xdistributefiles'
'xselect'
'ximportdir2dir'
'xreplaceheader'
'xdeletefiles'
'xrename'
'antkeys'
'xstat_2sampleTtest'
'xstat_anatomlabels'
};
f2={'xseldirs'
'xselectfiles'
};
disp(' ');
displaythat(2,f2)
displaythat(1,f)
function displaythat(modus,f)
format compact
f=sort(f);
f=cellfun(@(a) { [ strrep(a,'.m','') '.m' ] },f );
% disp(' ');
if modus==1
col=[1 .3 0];
col=['*[' num2str(col) ']'];
cprintf(col,' *** useful functions [showfun.m] ***\n');
cprintf(col,'*************************************\n');
elseif modus==2
col=[0.4667 0.6745 0.1882];
col=['*[' num2str(col) ']'];
cprintf(col,' *** useful subfunctions [showfun.m] ***\n');
cprintf(col,'*************************************\n');
end
for i=1:size(f,1)
% ff='antcb.m'
ff=f{i};
txt=help(ff);
h1=txt(1:min(strfind(txt,char(10))));
do_help=['showfunhelp(' '''' ff '''' ')'];
do_edit=['edit(' '''' ff '''' ')'];
disp([...' f <a href="matlab: ' do ' ">' ff '</a>' ' :' strrep(h1,char(10),'') ....
' <a href="matlab: ' do_edit ' ">' '[ed]' '</a>' ...
' <a href="matlab: ' do_help ' ">' ff '</a>' ...
strrep(h1,char(10),'')
]);
% disp([' f <a href="matlab: ' 'uhelp(g3(g2(g1(txt)),ff))' ' ">' ff '</a>' ' :' h1 ]);
% disp([' f <a href="matlab: ' '@dohelp(ff,h1, txt)' ' ">' ff '</a>' ' :' h1 ]);
end
|
github
|
philippboehmsturm/antx-master
|
calcMI.m
|
.m
|
antx-master/mritools/ant/calcMI.m
| 1,926 |
utf_8
|
5ad7ca887b51100634b905b7f9603c18
|
function param=calcMI(fi1,fi2)
%input: filepath or 3d volume
if ischar(fi1)
[ha a]=rgetnii(fi1);
else
a=fi1;
end
if ischar(fi2)
[hb b]=rreslice2target(fi2, fi1, [], 1);%rgetnii(fi2);rgetnii(fi2);
else
b=fi2;
end
%% no nan
a(isnan(a))=0;
b(isnan(b))=0;
%%mask of graymatter
% imask=b<.01;
% a(imask)=0;
% b(imask)=0;
% imask2=b>0;
% a=imask2.*a;
% b=imask2.*a;
% fg,
% subplot(2,2,1); imagesc(a(:,:,10));colorbar
% subplot(2,2,2); imagesc(b(:,:,10));colorbar
%% to integer
dynr=1024;%55;
a=a-min(a(:)); a=round((a./max(a(:))).*dynr);
b=b-min(b(:)); b=round((b./max(b(:))).*dynr);
miv=zeros(size(a,3),1);
for i=1:size(a,3)
miv(i)= mi2(a(:,:,i), b(:,:,i));
end
% miv=[;%]zeros(size(a,1),1);
% for i=1:size(a,1)
% miv(i)= mi2( squeeze(a(i,:,:)), squeeze(b(i,:,:)) );
% end
miv(miv==0)=[];
param=median(miv);
% disp([ mean(miv) median(miv) sum(miv) max(miv) ]);
function M = mi2(X,Y)
% function M = MI_GG(X,Y)
% Compute the mutual information of two images: X and Y, having
% integer values.
%
% INPUT:
% X --> first image
% Y --> second image (same size of X)
%
% OUTPUT:
% M --> mutual information of X and Y
%
% Written by GIANGREGORIO Generoso.
% DATE: 04/05/2012
% E-MAIL: [email protected]
%__________________________________________________________________________
X = double(X);
Y = double(Y);
X_norm = X - min(X(:)) +1;
Y_norm = Y - min(Y(:)) +1;
matAB(:,1) = X_norm(:);
matAB(:,2) = Y_norm(:);
h = accumarray(matAB+1, 1); % joint histogram
hn = h./sum(h(:)); % normalized joint histogram
y_marg=sum(hn,1);
x_marg=sum(hn,2);
Hy = - sum(y_marg.*log2(y_marg + (y_marg == 0))); % Entropy of Y
Hx = - sum(x_marg.*log2(x_marg + (x_marg == 0))); % Entropy of X
arg_xy2 = hn.*(log2(hn+(hn==0)));
h_xy = sum(-arg_xy2(:)); % joint entropy
M = Hx + Hy - h_xy; % mutual information
|
github
|
philippboehmsturm/antx-master
|
test_yair_listbox.m
|
.m
|
antx-master/mritools/ant/test_yair_listbox.m
| 2,182 |
utf_8
|
04a6eaeb4eec653b305dfb0489e57798
|
function bla
% Prepare the Matlab listbox uicontrol
hFig = figure;
listItems = {'apple','orange','banana','lemon','cherry','pear','melon'};
hListbox = uicontrol(hFig, 'style','listbox', 'units','norm', 'pos',[.1 .1 .4 .4], 'string',listItems);
% Get the listbox's underlying Java control
jScrollPane = findjobj(hListbox);
% We got the scrollpane container - get its actual contained listbox control
jListbox = jScrollPane.getViewport.getComponent(0);
% Convert to a callback-able reference handle
jListbox = handle(jListbox, 'CallbackProperties');
% Set the mouse-click callback
% Note: MousePressedCallback is better than MouseClickedCallback
% since it fires immediately when mouse button is pressed,
% without waiting for its release, as MouseClickedCallback does
set(jListbox, 'MousePressedCallback',{@myCallbackFcn,hListbox});
set(jListbox, 'MouseMovedCallback', {@mouseMovedCallback,hListbox});
% Mouse-movement callback
function mouseMovedCallback(jListbox, jEventData, hListbox)
% Get the currently-hovered list-item
mousePos = java.awt.Point(jEventData.getX, jEventData.getY);
hoverIndex = jListbox.locationToIndex(mousePos) + 1;
listValues = get(hListbox,'string');
hoverValue = listValues{hoverIndex};
% Modify the tooltip based on the hovered item
msgStr = sprintf('<html>item #%d: <b>%s</b></html>', hoverIndex, hoverValue);
set(hListbox, 'Tooltip',msgStr);
% Define the mouse-click callback function
function myCallbackFcn(jListbox,jEventData,hListbox)
% Determine the click type
% (can similarly test for CTRL/ALT/SHIFT-click)
if jEventData.isMetaDown % right-click is like a Meta-button
clickType = 'Right-click';
else
clickType = 'Left-click';
end
% Determine the current listbox index
% Remember: Java index starts at 0, Matlab at 1
mousePos = java.awt.Point(jEventData.getX, jEventData.getY);
clickedIndex = jListbox.locationToIndex(mousePos) + 1;
listValues = get(hListbox,'string');
clickedValue = listValues{clickedIndex};
fprintf('%s on item #%d (%s)\n', clickType, clickedIndex, clickedValue);
|
github
|
philippboehmsturm/antx-master
|
statusbar.m
|
.m
|
antx-master/mritools/ant/statusbar.m
| 12,591 |
utf_8
|
3513bd72623b8caa2bca356d4971b070
|
function statusbarHandles = statusbar(varargin)
%statusbar set/get the status-bar of Matlab desktop or a figure
%
% statusbar sets the status-bar text of the Matlab desktop or a figure.
% statusbar accepts arguments in the format accepted by the <a href="matlab:doc sprintf">sprintf</a>
% function and returns the statusbar handle(s), if available.
%
% Syntax:
% statusbarHandle = statusbar(handle, text, sprintf_args...)
%
% statusbar(text, sprintf_args...) sets the status bar text for the
% current figure. If no figure is selected, then one will be created.
% Note that figures with 'HandleVisibility' turned off will be skipped
% (compare <a href="matlab:doc findobj">findobj</a> & <a href="matlab:doc findall">findall</a>).
% In these cases, simply pass their figure handle as first argument.
% text may be a single string argument, or anything accepted by sprintf.
%
% statusbar(handle, ...) sets the status bar text of the figure
% handle (or the figure which contains handle). If the status bar was
% not yet displayed for this figure, it will be created and displayed.
% If text is not supplied, then any existing status bar is erased,
% unlike statusbar(handle, '') which just clears the text.
%
% statusbar(0, ...) sets the Matlab desktop's status bar text. If text is
% not supplied, then any existing text is erased, like statusbar(0, '').
%
% statusbar([handles], ...) sets the status bar text of all the
% requested handles.
%
% statusbarHandle = statusbar(...) returns the status bar handle
% for the selected figure. The Matlab desktop does not expose its
% statusbar object, so statusbar(0, ...) always returns [].
% If multiple unique figure handles were requested, then
% statusbarHandle is an array of all non-empty status bar handles.
%
% Notes:
% 1) The format statusbarHandle = statusbar(handle) does NOT erase
% any existing statusbar, but just returns the handles.
% 2) The status bar is 20 pixels high across the entire bottom of
% the figure. It hides everything between pixel heights 0-20,
% even parts of uicontrols, regardless of who was created first!
% 3) Three internal handles are exposed to the user (Figures only):
% - CornerGrip: a small square resizing grip on bottom-right corner
% - TextPanel: main panel area, containing the status text
% - ProgressBar: a progress bar within TextPanel (default: invisible)
%
% Examples:
% statusbar; % delete status bar from current figure
% statusbar(0, 'Desktop status: processing...');
% statusbar([hFig1,hFig2], 'Please wait while processing...');
% statusbar('Processing %d of %d (%.1f%%)...',idx,total,100*idx/total);
% statusbar('Running... [%s%s]',repmat('*',1,fix(N*idx/total)),repmat('.',1,N-fix(N*idx/total)));
% existingText = get(statusbar(myHandle),'Text');
%
% Examples customizing the status-bar appearance:
% sb = statusbar('text');
% set(sb.CornerGrip, 'visible',false);
% set(sb.TextPanel, 'Foreground',java.awt.Color(1,0,0), 'Background',java.awt.Color.cyan, 'ToolTipText','tool tip...')
% set(sb, 'Background',java.awt.Color.cyan);
%
% % sb.ProgressBar is by default invisible, determinite, non-continuous fill, min=0, max=100, initial value=0
% set(sb.ProgressBar, 'Visible',true, 'Minimum',0, 'Maximum',500, 'Value',234);
% set(sb.ProgressBar, 'Visible',true, 'Indeterminate',false); % indeterminate (annimated)
% set(sb.ProgressBar, 'Visible',true, 'StringPainted',true); % continuous fill
% set(sb.ProgressBar, 'Visible',true, 'StringPainted',true, 'string',''); % continuous fill, no percentage text
%
% % Adding a checkbox
% jCheckBox = javax.swing.JCheckBox('cb label');
% sb.add(jCheckBox,'West'); % Beware: East also works but doesn't resize automatically
% sb.revalidate; % update the display to show the new checkbox
%
% Technical description:
% http://UndocumentedMatlab.com/blog/setting-status-bar-text
% http://UndocumentedMatlab.com/blog/setting-status-bar-components
%
% Notes:
% Statusbar will probably NOT work on Matlab versions earlier than 6.0 (R12)
% In Matlab 6.0 (R12), figure statusbars are not supported (only desktop statusbar)
%
% Warning:
% This code heavily relies on undocumented and unsupported Matlab
% functionality. It works on Matlab 7+, but use at your own risk!
%
% Bugs and suggestions:
% Please send to Yair Altman (altmany at gmail dot com)
%
% Change log:
% 2007-04-25: First version posted on MathWorks file exchange: <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=14773">http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=14773</a>
% 2007-04-29: Added internal ProgressBar; clarified main comment
% 2007-05-04: Added partial support for Matlab 6
% 2011-10-14: Fix for R2011b
% 2014-10-13: Fix for R2014b
% 2015-03-22: Updated usage examples (no changes to the code)
%
% See also:
% ishghandle, sprintf, findjobj (on the <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=14317">file exchange</a>)
% License to use and modify this code is granted freely without warranty to all, as long as the original author is
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.
% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.7 $ $Date: 2015/03/22 11:52:24 $
% Check for available Java/AWT (not sure if Swing is really needed so let's just check AWT)
if ~usejava('awt')
error('YMA:statusbar:noJava','statusbar only works on Matlab envs that run on java');
end
% Args check
if nargin < 1 | ischar(varargin{1}) %#ok for Matlab 6 compatibility
handles = gcf; % note: this skips over figures with 'HandleVisibility'='off'
else
handles = varargin{1};
varargin(1) = [];
end
% Ensure that all supplied handles are valid HG GUI handles (Note: 0 is a valid HG handle)
if isempty(handles) | ~all(ishandle(handles)) %#ok for Matlab 6 compatibility
error('YMA:statusbar:invalidHandle','invalid GUI handle passed to statusbar');
end
% Retrieve the requested text string (only process once, for all handles)
if isempty(varargin)
deleteFlag = (nargout==0);
updateFlag = 0;
statusText = '';
else
deleteFlag = 0;
updateFlag = 1;
statusText = sprintf(varargin{:});
end
% Loop over all unique root handles (figures/desktop) of the supplied handles
rootHandles = [];
if any(double(handles)) % non-0, i.e. non-desktop
try
rootHandles = ancestor(handles,'figure');
if iscell(rootHandles), rootHandles = cell2mat(rootHandles); end
catch
errMsg = 'Matlab version is too old to support figure statusbars';
% Note: old Matlab version didn't have the ID optional arg in warning/error, so I can't use it here
if any(handles==0)
warning([errMsg, '. Updating the desktop statusbar only.']); %#ok for Matlab 6 compatibility
else
error(errMsg);
end
end
end
rootHandles = unique(rootHandles);
if any(double(handles)==0), rootHandles(end+1)=0; end
statusbarObjs = handle([]);
for rootIdx = 1 : length(rootHandles)
if rootHandles(rootIdx) == 0
setDesktopStatus(statusText);
else
thisStatusbarObj = setFigureStatus(rootHandles(rootIdx), deleteFlag, updateFlag, statusText);
if ~isempty(thisStatusbarObj)
statusbarObjs(end+1) = thisStatusbarObj;
end
end
end
% If statusbarHandles requested
if nargout
% Return the list of all valid (non-empty) statusbarHandles
statusbarHandles = statusbarObjs;
end
%end % statusbar %#ok for Matlab 6 compatibility
%% Set the status bar text of the Matlab desktop
function setDesktopStatus(statusText)
try
% First, get the desktop reference
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance; % Matlab 7+
catch
desktop = com.mathworks.ide.desktop.MLDesktop.getMLDesktop; % Matlab 6
end
% Schedule a timer to update the status text
% Note: can't update immediately, since it will be overridden by Matlab's 'busy' message...
try
t = timer('Name','statusbarTimer', 'TimerFcn',{@setText,desktop,statusText}, 'StartDelay',0.05, 'ExecutionMode','singleShot');
start(t);
catch
% Probably an old Matlab version that still doesn't have timer
desktop.setStatusText(statusText);
end
catch
%if any(ishandle(hFig)), delete(hFig); end
error('YMA:statusbar:desktopError',['error updating desktop status text: ' lasterr]);
end
%end %#ok for Matlab 6 compatibility
%% Utility function used as setDesktopStatus's internal timer's callback
function setText(varargin)
if nargin == 4 % just in case...
targetObj = varargin{3};
statusText = varargin{4};
targetObj.setStatusText(statusText);
else
% should never happen...
end
%end %#ok for Matlab 6 compatibility
%% Set the status bar text for a figure
function statusbarObj = setFigureStatus(hFig, deleteFlag, updateFlag, statusText)
try
jFrame = get(handle(hFig),'JavaFrame');
jFigPanel = get(jFrame,'FigurePanelContainer');
jRootPane = jFigPanel.getComponent(0).getRootPane;
% If invalid RootPane, retry up to N times
tries = 10;
while isempty(jRootPane) & tries>0 %#ok for Matlab 6 compatibility - might happen if figure is still undergoing rendering...
drawnow; pause(0.001);
tries = tries - 1;
jRootPane = jFigPanel.getComponent(0).getRootPane;
end
jRootPane = jRootPane.getTopLevelAncestor;
% Get the existing statusbarObj
statusbarObj = jRootPane.getStatusBar;
% If status-bar deletion was requested
if deleteFlag
% Non-empty statusbarObj - delete it
if ~isempty(statusbarObj)
jRootPane.setStatusBarVisible(0);
end
elseif updateFlag % status-bar update was requested
% If no statusbarObj yet, create it
if isempty(statusbarObj)
statusbarObj = com.mathworks.mwswing.MJStatusBar;
jProgressBar = javax.swing.JProgressBar;
jProgressBar.setVisible(false);
statusbarObj.add(jProgressBar,'West'); % Beware: East also works but doesn't resize automatically
jRootPane.setStatusBar(statusbarObj);
end
statusbarObj.setText(statusText);
jRootPane.setStatusBarVisible(1);
end
statusbarObj = handle(statusbarObj);
% Add quick references to the corner grip and status-bar panel area
if ~isempty(statusbarObj)
addOrUpdateProp(statusbarObj,'CornerGrip', statusbarObj.getParent.getComponent(0));
addOrUpdateProp(statusbarObj,'TextPanel', statusbarObj.getComponent(0));
addOrUpdateProp(statusbarObj,'ProgressBar', statusbarObj.getComponent(1).getComponent(0));
end
catch
try
try
title = jFrame.fFigureClient.getWindow.getTitle;
catch
title = jFrame.fHG1Client.getWindow.getTitle;
end
catch
title = get(hFig,'Name');
end
error('YMA:statusbar:figureError',['error updating status text for figure ' title ': ' lasterr]);
end
%end %#ok for Matlab 6 compatibility
%% Utility function: add a new property to a handle and update its value
function addOrUpdateProp(handle,propName,propValue)
try
if ~isprop(handle,propName)
schema.prop(handle,propName,'mxArray');
end
set(handle,propName,propValue);
catch
% never mind... - maybe propName is already in use
%lasterr
end
%end %#ok for Matlab 6 compatibility
|
github
|
philippboehmsturm/antx-master
|
calcGridcorr.m
|
.m
|
antx-master/mritools/ant/calcGridcorr.m
| 896 |
utf_8
|
82d8c053e6f2fc9ade16e0e8b3aa5a70
|
function param=calcGridcorr(fi1,fi2)
%input: filepath or 3d volume
if ischar(fi1)
[ha a]=rgetnii(fi1);
else
a=fi1;
end
if ischar(fi2)
[hb b]=rreslice2target(fi2, fi1, [], 1);%rgetnii(fi2);rgetnii(fi2);
else
b=fi2;
end
%% no nan
a(isnan(a))=0;
b(isnan(b))=0;
aa=permute(a,[1 3 2]);
bb=permute(b,[1 3 2]);
aa(aa<.01)=0;
% aa=aa-min(aa(:)); aa=255*(aa./max(aa(:)));
% bb=bb-min(bb(:)); bb=255*(bb./max(bb(:)));
nele=zeros(size(aa,3),2);
for i=1:size(aa,3)
nele(i,:)=[ length(unique(aa(:,:,i))) length(unique(bb(:,:,i))) ];
end
nslice=find(nele(:,1)>5 & nele(:,2)>5);
nslice=120:150;%# predefined
% zz=zeros(size(aa,3),3);
zz=zeros(length(nslice),3);
n=1;
for i=1:length(nslice)
[xmed xsum xme]=corrgrid(aa(:,:,nslice(i)),bb(:,:,nslice(i)), 5:20,0);
zz(n,:)=[xmed xsum xme];
n=n+1;
end
param=nanmean(zz);
|
github
|
philippboehmsturm/antx-master
|
struct2list.m
|
.m
|
antx-master/mritools/ant/struct2list.m
| 10,032 |
utf_8
|
76c55538a713e28f892eb0fa2b9f9489
|
%% convert struct to (executable) cell list (inDepth)
%% function ls=struct2list(x)
% -works with char, 1-2-3D numeric array, mixed cells
%% example
% w.project= 'TEST' ;
% w.voxsize= [0.07 0.07 0.07] ;
% w.datpath= 'O:\harms1\harmsTest_ANT\dat' ;
% w.brukerpath= 'O:\harms1\harmsTest_ANT\pvraw' ;
% w.refpa= 'V:\mritools\ant\templateBerlin_hres' ;
% w.refTPM = { 'V:\mritools\ant\templateBerlin_hres\_b1grey.nii'
% 'V:\mritools\ant\templateBerlin_hres\_b2white.nii'
% 'V:\mritools\ant\templateBerlin_hres\_b3csf.nii' };
% w.refsample= 'V:\mritools\ant\templateBerlin_hres\_sample.nii' ;
% w.a.b= 'hallo' ;
% w.x.e= [1 2 3] ;
% w.haus.auto = { 'YPL-320' 'Male' 38.00000 1.00000 176.00000
% 'GLI-532' 'Male' 43.00000 0.00000 163.00000
% 'PNI-258' 'Female' 38.00000 1.00000 131.00000
% 'MIJ-579' 'Female' 40.00000 0.00000 133.00000};
% w.O = { 'hello' 123.00000
% 3.14159 'bye' };
% w.O2 = { 'hello' 3.14159
% 123.00000 'bye' };
% w.d1= [1 2 3 4 5] ;
% w.d1v = [ 1
% 2
% 3
% 4
% 5 ];
% w.d2 = [ 1 0 1 1
% 0 1 1 1
% 1 1 1 1 ];
% w.d3(:,:,1) = [ 0.5800903658 0.1208595711
% 0.01698293834 0.8627107187 ];
% w.d3(:,:,2) = [ 0.4842965112 0.209405084
% 0.8448556746 0.5522913415 ];
% w.d3(:,:,3) = [ 0.6298833851 0.6147134191
% 0.03199101576 0.3624114623 ];
% w.r= [0.045673 1 1000 1.5678e+022 4.5678e-008] ;
% w.r2 = [ 0.045673 1 1000 1.5678e+022 4.5678e-008
% -1 -1 -1000 -1.5678e+022 -10 ];
% ls=struct2list(w)
function [ls varargout]=struct2list(x,varargin)
op=struct();
if nargin>1
c=varargin(1:2:end);
f=varargin(2:2:end);
op = cell2struct(f,c,2); %optional Parameters
%optional parameter: 'ntabs' number of tabs after ''
end
if 0
run('proj_harms_TESTSORDNER');
[pathx s]=antpath;
x= catstruct(x,s);
clear s
x.a.b='hallo'; x.x.e=[1 2 3];
x.haus.auto = {
'YPL-320', 'Male', 38, true, uint8(176);
'GLI-532', 'Male', 43, false, uint8(163);
'PNI-258', 'Female', 38, true, uint8(131);
'MIJ-579', 'Female', 40, false, uint8(133) };
x.O= {'hello', 123;pi, 'bye'};
x.O2= {'hello', 123;pi, 'bye'}';
% x=[]
x.d1=1:5;
x.d1v=[1:5]';
x.d2= logical(round(rand(3,4)*2-.5));
x.d3=rand(2,2,3);
x.r=([0.045673 1 1000 1.56780e22 .000000045678]);
x.r2=[[0.045673 1 1000 1.56780e22 .000000045678] ; -[[1 1 1000 1.56780e22 10.000000045678]]];
% t='x';
end
name=inputname(1);
eval([name '=x;' ]);
% fn= fieldnamesr(dum,'prefix');
eval(['fn= fieldnamesr(' name ',''prefix'');' ]);
s1={};
s2=s1;
if isfield(op,'ntabs')
ntabs=repmat('\t',1,op.ntabs);
else
ntabs='';
end
for i=1:size(fn,1)
eval(['d=' fn{i} ';']);
if isnumeric(d) | islogical(d)
%brackes empty, []
if size(d,1)==0
d2='[]';
s2{end+1,1}= sprintf(['%s=' ntabs '[%s];'],fn{i} , '');
end
if size(d,1)==1
% d2=sprintf('% 10.10g ' ,d);
d2=regexprep(num2str(d),'\s+',' ');
s2{end+1,1}= sprintf(['%s=' ntabs '[%s];'],fn{i} , d2);
elseif size(d,1)>1 && ndims(d)==2
g={};
for j=1:size(d,1)
d2=sprintf('%10.5g ' ,d(j,:));
g{end+1,1}= sprintf('%s%s ','' , d2) ;
end
p1=sprintf(['%s=' ntabs '%s '],fn{i} , '[');
p0=repmat(' ',[1 length(p1)]);
g=cellfun(@(g) {[ p0 g]} ,g) ;%space
g{1,1}(1:length(p1))=p1 ;%start
g{end}=[g{end} '];'] ; ;%end
% uhelp(g);set(findobj(gcf,'tag','txt'),'fontname','courier')
s2=[s2;g];
elseif size(d,1)>1 && ndims(d)==3
g2={};
for k=1:size(d,3)
g={};
for j=1:size(d,1)
d2=sprintf('%10.10g ' ,squeeze(d(j,:,k)));
g{end+1,1}= sprintf('%s %s','' , d2) ;
end
p1=sprintf([ '%s(:,:,%d)=' ntabs '[' ],fn{i} , k);
p0=repmat(' ',[1 length(p1)]);
g=cellfun(@(g) {[ p0 g]} ,g) ;%space
g{1,1}(1:length(p1))=p1 ;%start
g{end}=[g{end} '];'] ; ;%end
% uhelp(g);set(findobj(gcf,'tag','txt'),'fontname','courier')
g2=[g2;g];
end
s2=[s2;g2];
end
elseif ischar(d)
g=[ '''d'''];
s2{end+1,1}=sprintf(['%s=' ntabs '''%s'';'],fn{i} , d);
elseif iscell(d)
if isempty(d)
g= sprintf(['%s=' ntabs '{%s};'],fn{i} , '') ;
else
d2= (mat2clip(d));
s=sort([strfind(d2,char(10)) 0 length(d2)+1]);
g={};
for j=1: length(s)-1
g{end+1,1}=d2(s(j)+1:s(j+1)-1);
end
p1=sprintf(['%s=' ntabs '%s '],fn{i} , '{');
p0=repmat(' ',[1 length(p1)]);
g=cellfun(@(g) {[ p0 g]} ,g) ;%space
g{1,1}(1:length(p1))=p1 ;%start
g{end}=[g{end} '};'] ; ;%end
% uhelp(g);set(findobj(gcf,'tag','txt'),'fontname','courier')
end
s2=[s2;g];
end
end
% uhelp(s2,1);set(findobj(gcf,'tag','txt'),'fontname','courier')
ls=s2;
function out = mat2clip(a, delim)
% each element is separated by tabs and each row is separated by a NEWLINE
% character.
sep = {'\t', '\n', ''};
if nargin == 2
if ischar(delim)
sep{1} = delim;
else
error('mat2clip:CharacterDelimiter', ...
'Only character array for delimiters');
end
end
% try to determine the format of the numeric elements.
switch get(0, 'Format')
case 'short'
fmt = {'%s', '%0.5f' , '%d'};
case 'shortE'
fmt = {'%s', '%0.5e' , '%d'};
case 'shortG'
fmt = {'%s', '%0.5g' , '%d'};
case 'long'
fmt = {'%s', '%0.15f', '%d'};
case 'longE'
fmt = {'%s', '%0.15e', '%d'};
case 'longG'
fmt = {'%s', '%0.15g', '%d'};
otherwise
fmt = {'%s', '%0.5f' , '%d'};
end
fmt{1}='''%s'' ';
if iscell(a) % cell array
a = a';
floattypes = cellfun(@isfloat, a);
inttypes = cellfun(@isinteger, a);
logicaltypes = cellfun(@islogical, a);
strtypes = cellfun(@ischar, a);
classType = zeros(size(a));
classType(strtypes) = 1;
classType(floattypes) = 2;
classType(inttypes) = 3;
classType(logicaltypes) = 3;
if any(~classType(:))
error('mat2clip:InvalidDataTypeInCell', ...
['Invalid data type in the cell array. ', ...
'Only strings and numeric data types are allowed.']);
end
sepType = ones(size(a));
sepType(end, :) = 2; sepType(end) = 3;
tmp = [fmt(classType(:));sep(sepType(:))];
b=sprintf(sprintf('%s%s', tmp{:}), a{:});
elseif isfloat(a) % floating point number
a = a';
classType = repmat(2, size(a));
sepType = ones(size(a));
sepType(end, :) = 2; sepType(end) = 3;
tmp = [fmt(classType(:));sep(sepType(:))];
b=sprintf(sprintf('%s%s', tmp{:}), a(:));
elseif isinteger(a) || islogical(a) % integer types and logical
a = a';
classType = repmat(3, size(a));
sepType = ones(size(a));
sepType(end, :) = 2; sepType(end) = 3;
tmp = [fmt(classType(:));sep(sepType(:))];
b=sprintf(sprintf('%s%s', tmp{:}), a(:));
elseif ischar(a) % character array
% if multiple rows, convert to a single line with line breaks
if size(a, 1) > 1
b = cellstr(a);
b = [sprintf('%s\n', b{1:end-1}), b{end}];
else
b = a;
end
else
error('mat2clip:InvalidDataType', ...
['Invalid data type. ', ...
'Only cells, strings, and numeric data types are allowed.']);
end
% clipboard('copy', b);
out = b;
|
github
|
philippboehmsturm/antx-master
|
xcreatetemplatefiles2.m
|
.m
|
antx-master/mritools/ant/xcreatetemplatefiles2.m
| 2,351 |
utf_8
|
3415c9b89edaae6f0fa8c86688e9dc22
|
function t=xcreatetemplatefiles2(s,forcetooverwrite)
%% create templateFolder
patpl=s.templatepath;
if exist(patpl)~=7; mkdir(patpl); end
f1=s.avg;
f2 =fullfile(patpl,'AVGT.nii');
t.avg=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
[BB, vox] = world_bb(f1);
resize_img5(f1,f2, s.voxsize , BB, [], 1,[64 0]);
end
refimage=f2;
%% AVGTmask
makeMaskT3m(f2, fullfile(fileparts(f2),'AVGTmask.nii') , '>30');
f1=s.ano;
f2 =fullfile(patpl,'ANO.nii');
t.ano=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
rreslice2target(f1, refimage, f2, 0,[64 0]);
end
f1=s.fib;
f2 =fullfile(patpl,'FIBT.nii');
t.fib=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
rreslice2target(f1, refimage, f2, 0,[64 0]);
end
%% TPMS
f1=s.refTPM{1};
f2 =fullfile(patpl,'_b1grey.nii');
t.refTPM{1,1}=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
rreslice2target(f1, refimage, f2, 0,[2 0]);
end
f1=s.refTPM{2};
f2 =fullfile(patpl,'_b2white.nii');
t.refTPM{2,1}=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
rreslice2target(f1, refimage, f2, 0,[2 0]);
end
f1=s.refTPM{3};
f2 =fullfile(patpl,'_b3csf.nii');
t.refTPM{3,1}=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
rreslice2target(f1, refimage, f2, 0,[2 0]);
end
%% others
if s.create_gwc==1
ano=fullfile(patpl,'ANO.nii');
fib=fullfile(patpl,'FIBT.nii');
f2=fullfile(patpl,'GWC.nii');
t.gwc=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
xcreateGWC( ano,fib, f2 );
end
end
if s.create_anopcol==1
ano=fullfile(patpl,'ANO.nii');
f2=fullfile(patpl,'ANOpcol.nii');
t.anopcol=f2;
if any([~exist(f2,'file') forcetooverwrite])==1
disp(['generate: ' f2]);
[ha a]=rgetnii(ano);
% pseudocolor conversion
reg1=single(a);
uni=unique(reg1(:));
uni(find(uni==0))=[];
reg2=reg1.*0;
for l=1:length(uni)
reg2=reg2+(reg1==uni(l)).*l;
end
rsavenii(f2,ha,reg2,[4 0]);
end
end
|
github
|
philippboehmsturm/antx-master
|
foo.m
|
.m
|
antx-master/mritools/ant/foo.m
| 201 |
utf_8
|
37f29183fc41a85d4c663c9fc8579778
|
function fh=foo
fh.msub=@msub;
fh.madd=@madd;
fh.minfo=@minfo;
function r=msub(a,b)
r=a-b;
function r=madd(a,b)
r=a+b;
function [x y z]=minfo(a,b,c)
x='hallo'
y=[1:3]
z=b
|
github
|
philippboehmsturm/antx-master
|
createParallelpools.m
|
.m
|
antx-master/mritools/ant/createParallelpools.m
| 1,298 |
utf_8
|
f9133bdb62378d8761c3ca54e3cf1c60
|
%% open matlabpool depending on Matlab-version
% no args: open max number of pools
% args1: 'close' -->forces to close pools
%% EXAMPLES:
% createParallelpools;
% createParallelpools('close');
function createParallelpools(arg1)
if isempty(which('matlabpool')); %older versions
vers=1;
end
if isempty(which('paarpool')); %replaced in R2013b
vers=2;
end
%% open pool
if exist('arg1')~=1
if vers==1
mpools=[4 3 2];
for k=1:length(mpools)
try;
matlabpool(mpools(k));
disp(sprintf('process with %d PARALLEL-CORES',mppols(k)));
break
end
end
end
if vers==2
if isempty(gcp('nocreate'));
%local mpiexec disabled in version 2010a and newer
versrelease=version('-release');
if str2num(versrelease(1:end-1))>2010
distcomp.feature('LocalUseMpiexec',false);
end
parpool
end
end
return
end
%% close pool
if exist('arg1')==1
if strcmp(arg1,'close')
if vers==1
matlabpool close;
elseif vers==2
delete(gcp('nocreate'))
end
end
end
|
github
|
philippboehmsturm/antx-master
|
list2cell.m
|
.m
|
antx-master/mritools/ant/list2cell.m
| 1,964 |
utf_8
|
fdc67ca73a0234168471da6a39652a53
|
function c=list2cell(t,p)
% fn=fieldnames(x)
% t={}
% n=1;
% for i=1:length(fn)
% xx=getfield(x,fn{i})
% if ~isstruct(xx)
% t{n,1}=fn{i}
% t{n,2}=)=''
% n=n+1
% else
%
%
% end
% end
% t=char(txt);
% t=m
eval(t);
sp=[1 strfind(t,char(10)) length(t)];
t2={};
for i=1:length(sp)-1
dum=t(sp(i):sp(i+1));
t2{end+1,1}=strrep(dum,char(10),'');
end
%% get fieldnames
t3={};
n=1;
space=0;
for i=1:size(t2,1)
if isempty(t2{i})
continue
end
if strfind(t2{i},'% ')==1 %commment
if i>1
if isempty(t2{i-1})
space=1;
else
space=0;
end
end
if space ==0
t3(n,2) ={t2{i}(3:end)};
n=n+1;
else
t3(n,2) ={t2{i}(1:end)};
n=n+1;
end
else
eq= (strfind(t2{i},'='));
ec= (strfind(t2{i},'%'));
if ~isempty(eq)
if isempty(ec); ec=inf; end
if eq(1)<ec
t3(n,1)={t2{i}(1:eq(1)-1)};
n=n+1;
end
end
end
end
%% set variable
for i=1:size(t3,1)
if ~isempty(t3{i,1} )
eval(['dum=' t3{i,1} ';']);
t3{i,2}=dum;
t3{i,2}=dum;
end
end
%% set coment-varname
empt=find(cellfun('isempty',t3(:,1)));
emptref=regexpi2(p(:,1),'inf\d');
for i=1:length(empt)
id=regexpi2( regexprep(p(emptref,2),'\s','') ,regexprep(t3{empt(i),2},'\s','') );
t3{empt(i),1}=p{emptref(id),1};
end
%% set comments (3rd colum)
for i=1:size(t3,1)
id=regexpi2( regexprep(p(:,1),'^\s*x.',''), regexprep(t3{i,1},'^\s*x.',''));
if ~isempty(id)
t3{i,3}=p{i,3};
t3{i,4}=p{i,4};
else
t3{i,3}='';
t3{i,4}='';
end
end
%% remove( x.)
fn=regexprep(t3(:,1),'^\s*x.','');
c=[fn t3(:,2:end)];
|
github
|
philippboehmsturm/antx-master
|
xcopyfiles2.m
|
.m
|
antx-master/mritools/ant/xcopyfiles2.m
| 2,113 |
utf_8
|
7ee7c0537ad5a356b7f2fdc2caba4d2e
|
%% copy templates with given resolution
% function newfiles=xcopyfiles(rstruct, pa, voxres)
% INPUT
% struct: with FPfiles of templates (from antpath)
% pa : current mousepath (only the path)
% voxres: voxelResolution, e.g. : [0.07 0.07 0.07 ]
function newfiles=xcopyfiles2(rstruct, pa, voxres)
%% MAKE TEMPLATEPATH ()
[pas fi ext]=fileparts(pa);
if isempty(ext)
[pas2 fi2 ext2]=fileparts(pas);
end
templatepath=fullfile(pas2,'templates');
mkdir(templatepath);
%STRUCT TO CELL
rcell= struct2cell(rstruct);
isubcell=cellfun(@iscell,rcell);
% FIND CELLS WITHIN CELL
files=[ rcell(find(isubcell==0)) ];
files=[files; rcell{find(isubcell==1)}];
% ANO.nii is the reference FILE -->first IMAGE
iANO=regexpi2(files,'AVGT.nii');
files=[files(iANO) ; files(setdiff([1:length(files)],iANO)) ];
kdisp([' *** CREATE STUDY TEMPLATES *** ' ]);
kdisp([' this has to be done only once ' ]);
kdisp(['..create Templatefolder: ' templatepath]);
kdisp(['..reslice the following volumes to voxSize : [' sprintf('%2.2f ', voxres) ']']);
newfiles={};
for i=1:length(files)
if exist(files{i})==2
newfile=replacefilepath(files{i},templatepath);
[~ ,fis ,ext]=fileparts(newfile);
kdisp([' ... ' fis ext ]);
if i==1; %REFERENCE IMAGE
[BB, vox] = world_bb(files{i});
resize_img5(files{i},newfile, abs(voxres), BB, [], 1,[]);
refimage=newfile;
else %ALL OTHER IMAGES
interp=1;
if ~isempty(strfind(files{i},'ANO.nii')) || ~isempty(strfind(files{i},'FIBT.nii'))
interp=0;
end
rreslice2target(files{i}, refimage, newfile,interp);
end
newfiles(end+1,1)={newfile};
end
end
function kdisp(msg)
try
% cprintf([0 .5 0],(['warp: ' '[' num2str(i) '/' num2str(length(files)) ']: ' strrep(files{i},'\','\\') '\n'] ));
cprintf([0 .5 0],([ strrep(msg,[filesep],[filesep filesep]) '\n'] ));
catch
disp(msg);
end
|
github
|
philippboehmsturm/antx-master
|
antini.m
|
.m
|
antx-master/mritools/ant/antini.m
| 73 |
utf_8
|
94fff3f2aef7d40de43a8443c0f8569d
|
%% defaultparas
function iniparas=antini
iniparas.fontsize=9;
|
github
|
philippboehmsturm/antx-master
|
xsegment_test2.m
|
.m
|
antx-master/mritools/ant/xsegment_test2.m
| 6,419 |
utf_8
|
62407935968913f2a1ea8075a1de21f4
|
%% SEGMENT MOUSE
% function xsegment(t2,template)
% function xsegment(t2,template,job)...see below
% function xsegment(t2,template,'segment') %% SEGMENT ONLY without using Freiburg-normalization
%% INPUT:
% t2 : FPfile of t2.nii
% template: {cell} with ordered TPMs(GM,WM,CSF)+FPfile of reorient.mat
%% EXAMPLE
% t2='O:\harms1\koeln\dat\s20150701_BB1\t2.nii';
% template={ 'O:\harms1\koeln\dat\s20150701_BB1\_b1grey.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\_b2white.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\_b3csf.nii'
% 'O:\harms1\koeln\dat\s20150701_BB1\reorient.mat'}
% xsegment(t2,template)
function xsegment_test2(t2,template,job,mask)
t2destpath=fileparts(t2);
% b0only = 0;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file')
% options(4) = 4;
% else
% options = 0;
% end
% Preparing path names
% t2path = mouse.t2;
% t2destpath = mouse.outfolder;
% t2nii = cell(length(t2path));
% for k = 1:length(t2path),
% t2fullname = fullfile(t2destpath,['t2_' num2str(k)]);
% t2nii{k} = [t2fullname '.nii,1'];
% end
% Start of segmentation with t2.nii
% If t2.nii does not exist use b0.nii
cnt = 1;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file') == 2 && b0only == 0
matlabbatch{cnt}.spm.spatial.preproc.data = {t2} ;%{t2nii{1}}; %% T2file
matlabbatch{cnt}.spm.spatial.preproc.opts.warpreg = 1; % Original 1 (funzt okay: 50)
matlabbatch{cnt}.spm.spatial.preproc.opts.warpco = 1.75; % Original 1.75 (funzt okay: 2.5)
% else
% % matlabbatch{cnt}.spm.spatial.preproc.data = {fullfile(t2destpath,'b0.nii')};
% % matlabbatch{cnt}.spm.spatial.preproc.opts.warpreg = 1; % Original 1 (funzt okay: 50)
% % matlabbatch{cnt}.spm.spatial.preproc.opts.warpco = 1.75; % Original 1.75 (funzt okay: 2.5)
% end;
matlabbatch{cnt}.spm.spatial.preproc.output.GM = [0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.WM = [0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.CSF = [0 0 1];
matlabbatch{cnt}.spm.spatial.preproc.output.biascor = 1;
matlabbatch{cnt}.spm.spatial.preproc.output.cleanup = 0;
matlabbatch{cnt}.spm.spatial.preproc.opts.tpm = template; % Define Templates here
matlabbatch{cnt}.spm.spatial.preproc.opts.ngaus = [3
2
2
4];
matlabbatch{cnt}.spm.spatial.preproc.opts.regtype = 'animal'; % 'animal' / '';
matlabbatch{cnt}.spm.spatial.preproc.opts.biasreg = 0.0001;
matlabbatch{cnt}.spm.spatial.preproc.opts.biasfwhm = 5;
matlabbatch{cnt}.spm.spatial.preproc.opts.samp = 0.1;
matlabbatch{cnt}.spm.spatial.preproc.opts.msk = {mask};
cnt = cnt + 1;
% if exist(fullfile(mouse.outfolder, 't2_1.nii'),'file') && b0only == 0
matlabbatch{cnt}.spm.util.imcalc.input = {
fullfile(t2destpath,'c1t2.nii')
fullfile(t2destpath,'c2t2.nii')
};
% matlabbatch{cnt}.spm.util.imcalc.input = {
% fullfile(t2destpath,'c1t2_1.nii,1')
% fullfile(t2destpath,'c2t2_1.nii,1')
% };
% else
% matlabbatch{cnt}.spm.util.imcalc.input = {
% fullfile(t2destpath,'c1b0.nii,1')
% fullfile(t2destpath,'c2b0.nii,1')
% };
% end
matlabbatch{cnt}.spm.util.imcalc.output = 'c1c2mask.nii';
matlabbatch{cnt}.spm.util.imcalc.outdir = { t2destpath };
matlabbatch{cnt}.spm.util.imcalc.expression = '((i1 + i2)/2)>0.3';
matlabbatch{cnt}.spm.util.imcalc.options.dmtx = 0;
matlabbatch{cnt}.spm.util.imcalc.options.mask = 0;
matlabbatch{cnt}.spm.util.imcalc.options.interp = 1;
matlabbatch{cnt}.spm.util.imcalc.options.dtype = 4;
cnt = cnt + 1;
%% SEGMENT ONLY
if exist('job') && strcmp(job,'segment')
spm_jobman('serial', matlabbatch);
return
end
% Convert Deformation Parameters
% Convert deformation parameters to iy/y format (forward)
% if any(options == 4)
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_seg_sn.mat')};
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_1_seg_sn.mat')};
% else
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'b0_seg_sn.mat')};
% end
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.vox = [NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.bb = [NaN NaN NaN
NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.ofname = 'forward';
matlabbatch{cnt}.spm.util.defs.fnames = '';
matlabbatch{cnt}.spm.util.defs.savedir.savedef = 1;
matlabbatch{cnt}.spm.util.defs.interp = 4;
cnt = cnt + 1;
% Convert deformation parameters to iy/y format (inverse)
% if any(options == 4)
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_seg_inv_sn.mat')};
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'t2_1_seg_inv_sn.mat')};
% else
% matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.matname = {fullfile(t2destpath,'b0_seg_inv_sn.mat')};
% end
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.vox = [NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.comp{1}.sn2def.bb = [NaN NaN NaN
NaN NaN NaN];
matlabbatch{cnt}.spm.util.defs.ofname = 'inverse';
matlabbatch{cnt}.spm.util.defs.fnames = {''};
matlabbatch{cnt}.spm.util.defs.savedir.savedef = 1;
matlabbatch{cnt}.spm.util.defs.interp = 4;
% Realign deformations to original template space
cnt = cnt + 1;
matlabbatch{cnt}.dtijobs.realigndef.yname = {fullfile(t2destpath,'y_forward.nii')};
matlabbatch{cnt}.dtijobs.realigndef.iyname = {fullfile(t2destpath,'y_inverse.nii')};
matlabbatch{cnt}.dtijobs.realigndef.matname = template(end);%template(4);
% return
spm_jobman('serial', matlabbatch);
|
github
|
philippboehmsturm/antx-master
|
startspmd.m
|
.m
|
antx-master/mritools/ant/startspmd.m
| 587 |
utf_8
|
eeddee0935107904f719bad8735eaa85
|
function startspmd(an, paths,tasks)
createParallelpools;
disp('..PCT-SPMD used');
atime=tic;
%% SPMD
% global an
spmd
for j = labindex:numlabs:length(paths) %% j=1:length(paths)
for i=1:size(tasks,1)
%try
% i,j, paths{j}
try
disp(sprintf('%d, %d -%s',j,i,paths{j} ));
antfun(tasks{i},paths{j},tasks{i,2:end},an);
end
%catch
% &antfun(tasks{i,1},paths{j});
%end
end %i
end
end %spmd
toc(atime);
|
github
|
philippboehmsturm/antx-master
|
loadspmmouse.m
|
.m
|
antx-master/mritools/ant/loadspmmouse.m
| 207 |
utf_8
|
a03041ab2e05dbbd848f56ce27cc515b
|
function loadspmmouse
mtlbfolder = which('spmmouse');
sprts = findstr(mtlbfolder,filesep);
mtlbfolder=fullfile(mtlbfolder(1:sprts(end)),'mouse-C57.mat');
spmmouse('load',mtlbfolder);
|
github
|
philippboehmsturm/antx-master
|
useotherspm.m
|
.m
|
antx-master/mritools/ant/useotherspm.m
| 503 |
utf_8
|
dde3563dceb556fb6d4a6794759d4333
|
%% uses other spm (xspm) for display (freiburg is broken)
function useotherspm(arg)
warning off;
if exist('arg')==0;
arg=1;
end
if arg==1 %add
dirx=fullfile( fileparts(fileparts(fileparts(which('ant.m')))) , 'xspm8' );
addpath(dirx);
elseif arg==0 %remove
dirx=fullfile( fileparts(fileparts(fileparts(which('ant.m')))) , 'xspm8' );
rmpath(genpath(dirx));
else
error('cant use other SPMversion');
end
%spmmouse('load',which('mouse-C57.mat'))
|
github
|
philippboehmsturm/antx-master
|
xcopyfiles.m
|
.m
|
antx-master/mritools/ant/xcopyfiles.m
| 2,112 |
utf_8
|
94c957a1578c978f07f558946bd4697b
|
%% copy templates with given resolution
% function newfiles=xcopyfiles(rstruct, pa, voxres)
% INPUT
% struct: with FPfiles of templates (from antpath)
% pa : current mousepath (only the path)
% voxres: voxelResolution, e.g. : [0.07 0.07 0.07 ]
function newfiles=xcopyfiles(rstruct, pa, voxres)
%% MAKE TEMPLATEPATH ()
[pas fi ext]=fileparts(pa);
if isempty(ext)
[pas2 fi2 ext2]=fileparts(pas);
end
templatepath=fullfile(pas2,'templates');
mkdir(templatepath);
%STRUCT TO CELL
rcell= struct2cell(rstruct);
isubcell=cellfun(@iscell,rcell);
% FIND CELLS WITHIN CELL
files=[ rcell(find(isubcell==0)) ];
files=[files; rcell{find(isubcell==1)}];
% ANO.nii is the reference FILE -->first IMAGE
iANO=regexpi2(files,'AVGT.nii');
files=[files(iANO) ; files(setdiff([1:length(files)],iANO)) ];
kdisp([' *** CREATE STUDY TEMPLATES *** ' ]);
kdisp([' this has to be done only once ' ]);
kdisp(['..create Templatefolder: ' templatepath]);
kdisp(['..reslice the following volumes to voxSize : [' sprintf('%2.2f ', voxres) ']']);
newfiles={};
for i=1:length(files)
if exist(files{i})==2
newfile=replacefilepath(files{i},templatepath);
[~ ,fis ,ext]=fileparts(newfile);
kdisp([' ... ' fis ext ]);
if i==1; %REFERENCE IMAGE
[BB, vox] = world_bb(files{i});
resize_img5(files{i},newfile, abs(voxres), BB, [], 1,[]);
refimage=newfile;
else %ALL OTHER IMAGES
interp=1;
if ~isempty(strfind(files{i},'ANO.nii')) || ~isempty(strfind(files{i},'FIBT.nii'))
interp=0;
end
rreslice2target(files{i}, refimage, newfile,interp);
end
newfiles(end+1,1)={newfile};
end
end
function kdisp(msg)
try
% cprintf([0 .5 0],(['warp: ' '[' num2str(i) '/' num2str(length(files)) ']: ' strrep(files{i},'\','\\') '\n'] ));
cprintf([0 .5 0],([ strrep(msg,[filesep],[filesep filesep]) '\n'] ));
catch
disp(msg);
end
|
github
|
philippboehmsturm/antx-master
|
exportfig.m
|
.m
|
antx-master/mritools/ant/exportfig.m
| 13,007 |
utf_8
|
45c6593c96493d64183aa1a414cf670e
|
function exportfig(varargin)
%EXPORTFIG Export a figure to Encapsulated Postscript.
% EXPORTFIG(H, FILENAME) writes the figure H to FILENAME. H is
% a figure handle and FILENAME is a string that specifies the
% name of the output file.
%
% EXPORTFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies
% parameters that control various characteristics of the output
% file.
%
% Format Paramter:
% 'Format' one of the strings 'eps','eps2','jpeg','png'
% specifies the output format. Defaults to 'eps'.
%
% Size Parameters:
% 'Width' a positive scalar
% specifies the width in the figure's PaperUnits
% 'Height' a positive scalar
% specifies the height in the figure's PaperUnits
%
% Specifying only one dimension sets the other dimension
% so that the exported aspect ratio is the same as the
% figure's current aspect ratio.
% If neither dimension is specified the size defaults to
% the width and height from the figure's PaperPosition.
%
% Rendering Parameters:
% 'Color' one of the strings 'bw', 'gray', 'cmyk'
% 'bw' specifies that lines and text are exported in
% black and all other objects in grayscale
% 'gray' specifies that all objects are exported in grayscale
% 'cmyk' specifies that all objects are exported in color
% using the CMYK color space
% 'Renderer' one of the strings 'painters', 'zbuffer', 'opengl'
% specifies the renderer to use
% 'Resolution' a positive scalar
% specifies the resolution in dots-per-inch.
%
% The default color setting is 'bw'.
%
% Font Parameters:
% 'FontMode' one of the strings 'scaled', 'fixed'
% 'FontSize' a positive scalar
% in 'scaled' mode multiplies with the font size of each
% text object to obtain the exported font size
% in 'fixed' mode specifies the font size of all text
% objects in points
% 'FontEncoding' one of the strings 'latin1', 'adobe'
% specifies the character encoding of the font
%
% If FontMode is 'scaled' but FontSize is not specified then a
% scaling factor is computed from the ratio of the size of the
% exported figure to the size of the actual figure. The minimum
% font size allowed after scaling is 5 points.
% If FontMode is 'fixed' but FontSize is not specified then the
% exported font sizes of all text objects is 7 points.
%
% The default 'FontMode' setting is 'scaled'.
%
% Line Width Parameters:
% 'LineMode' one of the strings 'scaled', 'fixed'
% 'LineWidth' a positive scalar
% the semantics of LineMode and LineWidth are exactly the
% same as FontMode and FontSize, except that they apply
% to line widths instead of font sizes. The minumum line
% width allowed after scaling is 0.5 points.
% If LineMode is 'fixed' but LineWidth is not specified
% then the exported line width of all line objects is 1
% point.
%
% Examples:
% exportfig(gcf,'fig1.eps','height',3);
% Exports the current figure to the file named 'fig1.eps' with
% a height of 3 inches (assuming the figure's PaperUnits is
% inches) and an aspect ratio the same as the figure's aspect
% ratio on screen.
%
% exportfig(gcf, 'fig2.eps', 'FontMode', 'fixed',...
% 'FontSize', 10, 'color', 'cmyk' );
% Exports the current figure to 'fig2.eps' in color with all
% text in 10 point fonts. The size of the exported figure is
% the figure's PaperPostion width and height.
if (nargin < 2)
error('Too few input arguments');
end
% exportfig(H, filename, ...)
H = varargin{1};
filename = varargin{2};
paramPairs = varargin(3:end);
% Do some validity checking on param-value pairs
if (rem(length(paramPairs),2) ~= 0)
error(['Invalid input syntax. Optional parameters and values' ...
' must be in pairs.']);
end
format = 'eps';
width = -1;
height = -1;
color = 'bw';
fontsize = -1;
fontmode='scaled';
linewidth = -1;
linemode=[];
fontencoding = 'latin1';
renderer = [];
resolution = [];
% Process param-value pairs
args = {};
for k = 1:2:length(paramPairs)
param = lower(paramPairs{k});
if (~ischar(param))
error('Optional parameter names must be strings');
end
value = paramPairs{k+1};
switch (param)
case 'format'
format = value;
if (~strcmp(format,{'eps','eps2','jpeg','png'}))
error('Format must be ''eps'', ''eps2'', ''jpeg'' or ''png''.');
end
case 'width'
width = value;
if(~LocalIsPositiveScalar(width))
error('Width must be a numeric scalar > 0');
end
case 'height'
height = value;
if(~LocalIsPositiveScalar(height))
error('Height must be a numeric scalar > 0');
end
case 'color'
color = lower(value);
if (~strcmp(color,{'bw','gray','cmyk'}))
error('Color must be ''bw'', ''gray'' or ''cmyk''.');
end
case 'fontmode'
fontmode = lower(value);
if (~strcmp(fontmode,{'scaled','fixed'}))
error('FontMode must be ''scaled'' or ''fixed''.');
end
case 'fontsize'
fontsize = value;
if(~LocalIsPositiveScalar(fontsize))
error('FontSize must be a numeric scalar > 0');
end
case 'fontencoding'
fontencoding = lower(value);
if (~strcmp(fontencoding,{'latin1','adobe'}))
error('FontEncoding must be ''latin1'' or ''adobe''.');
end
case 'linemode'
linemode = lower(value);
if (~strcmp(linemode,{'scaled','fixed'}))
error('LineMode must be ''scaled'' or ''fixed''.');
end
case 'linewidth'
linewidth = value;
if(~LocalIsPositiveScalar(linewidth))
error('LineWidth must be a numeric scalar > 0');
end
case 'renderer'
renderer = lower(value);
if (~strcmp(renderer,{'painters','zbuffer','opengl'}))
error('Renderer must be ''painters'', ''zbuffer'' or ''opengl''.');
end
case 'resolution'
resolution = value;
if ~(isnumeric(value) & (prod(size(value)) == 1) & (value >= 0));
error('Resolution must be a numeric scalar >= 0');
end
otherwise
error(['Unrecognized option ' param '.']);
end
end
allLines = findall(H, 'type', 'line');
allText = findall(H, 'type', 'text');
allAxes = findall(H, 'type', 'axes');
allImages = findall(H, 'type', 'image');
allLights = findall(H, 'type', 'light');
allPatch = findall(H, 'type', 'patch');
allSurf = findall(H, 'type', 'surface');
allRect = findall(H, 'type', 'rectangle');
allFont = [allText; allAxes];
allColor = [allLines; allText; allAxes; allLights];
allMarker = [allLines; allPatch; allSurf];
allEdge = [allPatch; allSurf];
allCData = [allImages; allPatch; allSurf];
old.objs = {};
old.prop = {};
old.values = {};
% Process size parameters
paperPos = get(H, 'PaperPosition');
old = LocalPushOldData(old, H, 'PaperPosition', paperPos);
figureUnits = get(H, 'Units');
set(H, 'Units', get(H,'PaperUnits'));
figurePos = get(H, 'Position');
aspectRatio = figurePos(3)/figurePos(4);
set(H, 'Units', figureUnits);
if (width == -1) & (height == -1)
width = paperPos(3);
height = paperPos(4);
elseif (width == -1)
width = height * aspectRatio;
elseif (height == -1)
height = width / aspectRatio;
end
set(H, 'PaperPosition', [0 0 width height]);
paperPosMode = get(H, 'PaperPositionMode');
old = LocalPushOldData(old, H, 'PaperPositionMode', paperPosMode);
set(H, 'PaperPositionMode', 'manual');
% Process rendering parameters
switch (color)
case {'bw', 'gray'}
if ~strcmp(color,'bw') & strncmp(format,'eps',3)
format = [format 'c'];
end
args = {args{:}, ['-d' format]};
%compute and set gray colormap
oldcmap = get(H,'Colormap');
newgrays = 0.30*oldcmap(:,1) + 0.59*oldcmap(:,2) + 0.11*oldcmap(:,3);
newcmap = [newgrays newgrays newgrays];
old = LocalPushOldData(old, H, 'Colormap', oldcmap);
set(H, 'Colormap', newcmap);
%compute and set ColorSpec and CData properties
old = LocalUpdateColors(allColor, 'color', old);
old = LocalUpdateColors(allAxes, 'xcolor', old);
old = LocalUpdateColors(allAxes, 'ycolor', old);
old = LocalUpdateColors(allAxes, 'zcolor', old);
old = LocalUpdateColors(allMarker, 'MarkerEdgeColor', old);
old = LocalUpdateColors(allMarker, 'MarkerFaceColor', old);
old = LocalUpdateColors(allEdge, 'EdgeColor', old);
old = LocalUpdateColors(allEdge, 'FaceColor', old);
old = LocalUpdateColors(allCData, 'CData', old);
case 'cmyk'
if strncmp(format,'eps',3)
format = [format 'c'];
args = {args{:}, ['-d' format], '-cmyk'};
else
args = {args{:}, ['-d' format]};
end
otherwise
error('Invalid Color parameter');
end
if (~isempty(renderer))
args = {args{:}, ['-' renderer]};
end
if (~isempty(resolution))
args = {args{:}, ['-r' int2str(resolution)]};
end
% Process font parameters
if (~isempty(fontmode))
oldfonts = LocalGetAsCell(allFont,'FontSize');
switch (fontmode)
case 'fixed'
oldfontunits = LocalGetAsCell(allFont,'FontUnits');
old = LocalPushOldData(old, allFont, {'FontUnits'}, oldfontunits);
set(allFont,'FontUnits','points');
if (fontsize == -1)
set(allFont,'FontSize',7);
else
set(allFont,'FontSize',fontsize);
end
case 'scaled'
if (fontsize == -1)
wscale = width/figurePos(3);
hscale = height/figurePos(4);
scale = min(wscale, hscale);
else
scale = fontsize;
end
newfonts = LocalScale(oldfonts,scale,5);
set(allFont,{'FontSize'},newfonts);
otherwise
error('Invalid FontMode parameter');
end
% make sure we push the size after the units
old = LocalPushOldData(old, allFont, {'FontSize'}, oldfonts);
end
if strcmp(fontencoding,'adobe') & strncmp(format,'eps',3)
args = {args{:}, '-adobecset'};
end
% Process linewidth parameters
if (~isempty(linemode))
oldlines = LocalGetAsCell(allLines,'LineWidth');
old = LocalPushOldData(old, allLines, {'LineWidth'}, oldlines);
switch (linemode)
case 'fixed'
if (linewidth == -1)
set(allLines,'LineWidth',1);
else
set(allLines,'LineWidth',linewidth);
end
case 'scaled'
if (linewidth == -1)
wscale = width/figurePos(3);
hscale = height/figurePos(4);
scale = min(wscale, hscale);
else
scale = linewidth;
end
newlines = LocalScale(oldlines, scale, 0.5);
set(allLines,{'LineWidth'},newlines);
otherwise
error('Invalid LineMode parameter');
end
end
% Export
print(H, filename, args{:});
% Restore figure settings
for n=1:length(old.objs)
set(old.objs{n}, old.prop{n}, old.values{n});
end
%
% Local Functions
%
function [outData] = LocalPushOldData(inData, objs, prop, values)
outData.objs = {inData.objs{:}, objs};
outData.prop = {inData.prop{:}, prop};
outData.values = {inData.values{:}, values};
function [cellArray] = LocalGetAsCell(fig,prop);
cellArray = get(fig,prop);
if (~isempty(cellArray)) & (~iscell(cellArray))
cellArray = {cellArray};
end
function [newArray] = LocalScale(inArray, scale, minValue)
n = length(inArray);
newArray = cell(n,1);
for k=1:n
newArray{k} = max(minValue,scale*inArray{k}(1));
end
function [newArray] = LocalMapToGray(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
color = inArray{k};
if (~isempty(color))
if ischar(color)
switch color(1)
case 'y'
color = [1 1 0];
case 'm'
color = [1 0 1];
case 'c'
color = [0 1 1];
case 'r'
color = [1 0 0];
case 'g'
color = [0 1 0];
case 'b'
color = [0 0 1];
case 'w'
color = [1 1 1];
case 'k'
color = [0 0 0];
otherwise
newArray{k} = color;
end
end
if ~ischar(color)
color = 0.30*color(1) + 0.59*color(2) + 0.11*color(3);
end
end
if isempty(color) | ischar(color)
newArray{k} = color;
else
newArray{k} = [color color color];
end
end
function [newArray] = LocalMapCData(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
color = inArray{k};
if (ndims(color) == 3)
gray = 0.30*color(:,:,1) + 0.59*color(:,:,2) + 0.11*color(:,:,3);
color(:,:,1) = gray;
color(:,:,2) = gray;
color(:,:,3) = gray;
end
newArray{k} = color;
end
function [outData] = LocalUpdateColors(inArray, prop, inData)
value = LocalGetAsCell(inArray,prop);
outData.objs = {inData.objs{:}, inArray};
outData.prop = {inData.prop{:}, {prop}};
outData.values = {inData.values{:}, value};
if (~isempty(value))
if strcmp(prop,'CData')
value = LocalMapCData(value);
else
value = LocalMapToGray(value);
end
set(inArray,{prop},value);
end
function [bool] = LocalIsPositiveScalar(value)
bool = isnumeric(value) & ...
prod(size(value)) == 1 & ...
value > 0;
|
github
|
philippboehmsturm/antx-master
|
parcelate.m
|
.m
|
antx-master/mritools/ant/parcelate.m
| 852 |
utf_8
|
1e9da69fdfcd0fe6ba1835745bb689d7
|
function [w3 bord]=parcelate(w,nbox, plotter)
warning off;
if 0
load('mandrill')
w=imresize(X,[402 410]);
% w=rand(402,410);
nbox=4;
end
si=size(w);
% l1=round (linspace(1,si(1), nbox+1))
% l2=round (linspace(1,si(2), nbox+1))
r1=mod(si(1),4);
r2=mod(si(2),4);
si2=si-[r1 r2];
w2=imresize(w,si2);
si3=si2/nbox;
% w3=reshape(w2,[si3 numel(w2)/(prod(si3)) ]);
l1=[1:si3(1):si2(1) si2(1)+1];
l2=[1:si3(2):si2(2) si2(2)+1];
n=1;
bord=[];
for i=1:length(l1)-1
for j=1:length(l2)-1
s1=l1(i):l1(i+1)-1;
s2=l2(j):l2(j+1)-1;
% w3(:,:,n)=w2(s1,s2);
bord(n,:)=round([s1([1 end]) s2([1 end])]); %borders
w3(:,:,n)=w2(l1(i):l1(i+1)-1, l2(j):l2(j+1)-1);
n=n+1;
end
end
if plotter==1
fg; montage_p(w3)
end
|
github
|
philippboehmsturm/antx-master
|
corrgrid.m
|
.m
|
antx-master/mritools/ant/corrgrid.m
| 1,501 |
utf_8
|
b0e7802a92d4f635bc5f6f48b5144453
|
% function [xmed xsum]=corrgrid(q,z, nboxes,plotter)
% [xmed xsum]=corrgrid(q,z, 1:10,1);
% [xmed xsum]=corrgrid(q,z(:,:,1), 1:10,1)
%q: 2d image
% z : 2d or 3d (stack of images)
function [xmed xsum xme]=corrgrid(q,z, nboxes,plotter)
q=double(q);
z=double(z);
%% corr2 loop
if 0
% z=d(:,:,v);
z=d(:,:,:);%
q=m2;
nboxes=[5:10]
plotter=1
end
% nbox=4;rr=[];
numx=0;
for nbox=nboxes
numx=numx+1;
u2=q;
% u2=medfilt2(u2);
p2=parcelate(u2,nbox,0);
for j=1:size(z,3)
u1=z(:,:,j);
% u1=medfilt2(u1);
p1=parcelate(u1,nbox,0);
for i=1:size(p1,3)
rr(i,j,numx)=corr2(p1(:,:,i),p2(:,:,i));
end
end
end
rr=abs(rr);
rr(rr==0)=nan;
rr2=permute(rr,[1 3 2]);
rr2=reshape(rr2,[ size(rr2,1)*size(rr2,2) size(rr2,3)]);
xsum =nansum(rr2,1);
xmed=nanmedian(rr2,1);
xme=nanmean(rr2,1);
xnum=median(sum(~isnan(rr2)));
% xnum
try
if plotter==1
ma1=find(xsum==max(xsum));
ma2=find(xmed==max(xmed));
ma3=find(xme==max(xme));
fg;
subplot(2,2,1); plot(xsum,'-r.'); title(['nansum : max ' num2str(ma1)]); hold on; plot(ma1,xsum(ma1),'db');
subplot(2,2,2); plot(xmed,'-r.'); title(['nanmdian : max ' num2str(ma2)]); hold on; plot(ma2,xmed(ma2),'db');
subplot(2,2,3); plot(xme,'-r.'); title(['nanmean : max ' num2str(ma3)]); hold on; plot(ma3,xme(ma3),'db');
end
end
|
github
|
philippboehmsturm/antx-master
|
xcreateGWC.m
|
.m
|
antx-master/mritools/ant/xcreateGWC.m
| 975 |
utf_8
|
cad3562ff977bc6c27fc9e5d428026dd
|
function xcreateGWC(anofile,fibfile, GWCoutfile)
% anofile=fullfile(pas,'ANO.nii')
% fibfile=fullfile(pas,'FIBT.nii')
[ha a xyz XYZ]= rgetnii(anofile);
[hb b] = rgetnii(fibfile);
a2=a;
a2(a2~=8 & a2~=0)=1;
a2(a2==8)=0;
b(b~=0)=1;
c=a2+b;
% rsavenii('test.nii',ha,c);
%----------------------
si=size(a);
c=single(a==8 & b==0);
% rsavenii('testCSF.nii',ha,c)
c2=single(c(:));
idx=find(c2==1);
s=spm_clusters3(XYZ(:,idx) );
st=tabulate(s);
st=flipud(sortrows(st,2));
num2code=6;
s2=single(zeros(length(s),1));
for i=1:num2code
id=st(i,1);
inum=find(s==id);
s2(inum)=i;
end
c3=zeros(size(c2));
c3(idx)=s2;
c4=reshape(c3,si);
c4(c4>0)=1;
d=a2+b+c4;
% rsavenii('test_1.nii',ha,a2)
% rsavenii('test_2.nii',ha,b)
% rsavenii('test_3.nii',ha,c4)
dum=a2+(b*2);
dum(dum==3)=2;%replace 3...
dum=dum+(c4*3);
rsavenii(GWCoutfile,ha, dum ,[2 0]);
|
github
|
philippboehmsturm/antx-master
|
fdr_bh.m
|
.m
|
antx-master/mritools/ant/fdr_bh.m
| 9,039 |
utf_8
|
6ee458c4ce61569d12d9b362c8b4c276
|
% fdr_bh() - Executes the Benjamini & Hochberg (1995) and the Benjamini &
% Yekutieli (2001) procedure for controlling the false discovery
% rate (FDR) of a family of hypothesis tests. FDR is the expected
% proportion of rejected hypotheses that are mistakenly rejected
% (i.e., the null hypothesis is actually true for those tests).
% FDR is a somewhat less conservative/more powerful method for
% correcting for multiple comparisons than procedures like Bonferroni
% correction that provide strong control of the family-wise
% error rate (i.e., the probability that one or more null
% hypotheses are mistakenly rejected).
%
% This function also returns the false coverage-statement rate
% (FCR)-adjusted selected confidence interval coverage (i.e.,
% the coverage needed to construct multiple comparison corrected
% confidence intervals that correspond to the FDR-adjusted p-values).
%
%
% Usage:
% >> [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(pvals,q,method,report);
%
% Required Input:
% pvals - A vector or matrix (two dimensions or more) containing the
% p-value of each individual test in a family of tests.
%
% Optional Inputs:
% q - The desired false discovery rate. {default: 0.05}
% method - ['pdep' or 'dep'] If 'pdep,' the original Bejnamini & Hochberg
% FDR procedure is used, which is guaranteed to be accurate if
% the individual tests are independent or positively dependent
% (e.g., Gaussian variables that are positively correlated or
% independent). If 'dep,' the FDR procedure
% described in Benjamini & Yekutieli (2001) that is guaranteed
% to be accurate for any test dependency structure (e.g.,
% Gaussian variables with any covariance matrix) is used. 'dep'
% is always appropriate to use but is less powerful than 'pdep.'
% {default: 'pdep'}
% report - ['yes' or 'no'] If 'yes', a brief summary of FDR results are
% output to the MATLAB command line {default: 'no'}
%
%
% Outputs:
% h - A binary vector or matrix of the same size as the input "pvals."
% If the ith element of h is 1, then the test that produced the
% ith p-value in pvals is significant (i.e., the null hypothesis
% of the test is rejected).
% crit_p - All uncorrected p-values less than or equal to crit_p are
% significant (i.e., their null hypotheses are rejected). If
% no p-values are significant, crit_p=0.
% adj_ci_cvrg - The FCR-adjusted BH- or BY-selected
% confidence interval coverage. For any p-values that
% are significant after FDR adjustment, this gives you the
% proportion of coverage (e.g., 0.99) you should use when generating
% confidence intervals for those parameters. In other words,
% this allows you to correct your confidence intervals for
% multiple comparisons. You can NOT obtain confidence intervals
% for non-significant p-values. The adjusted confidence intervals
% guarantee that the expected FCR is less than or equal to q
% if using the appropriate FDR control algorithm for the
% dependency structure of your data (Benjamini & Yekutieli, 2005).
% FCR (i.e., false coverage-statement rate) is the proportion
% of confidence intervals you construct
% that miss the true value of the parameter. adj_ci=NaN if no
% p-values are significant after adjustment.
% adj_p - All adjusted p-values less than or equal to q are significant
% (i.e., their null hypotheses are rejected). Note, adjusted
% p-values can be greater than 1.
%
%
% References:
% Benjamini, Y. & Hochberg, Y. (1995) Controlling the false discovery
% rate: A practical and powerful approach to multiple testing. Journal
% of the Royal Statistical Society, Series B (Methodological). 57(1),
% 289-300.
%
% Benjamini, Y. & Yekutieli, D. (2001) The control of the false discovery
% rate in multiple testing under dependency. The Annals of Statistics.
% 29(4), 1165-1188.
%
% Benjamini, Y., & Yekutieli, D. (2005). False discovery rate?adjusted
% multiple confidence intervals for selected parameters. Journal of the
% American Statistical Association, 100(469), 71?81. doi:10.1198/016214504000001907
%
%
% Example:
% nullVars=randn(12,15);
% [~, p_null]=ttest(nullVars); %15 tests where the null hypothesis
% %is true
% effectVars=randn(12,5)+1;
% [~, p_effect]=ttest(effectVars); %5 tests where the null
% %hypothesis is false
% [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh([p_null p_effect],.05,'pdep','yes');
% data=[nullVars effectVars];
% fcr_adj_cis=NaN*zeros(2,20); %initialize confidence interval bounds to NaN
% if ~isnan(adj_ci_cvrg),
% sigIds=find(h);
% fcr_adj_cis(:,sigIds)=tCIs(data(:,sigIds),adj_ci_cvrg); % tCIs.m is available on the
% %Mathworks File Exchagne
% end
%
%
% For a review of false discovery rate control and other contemporary
% techniques for correcting for multiple comparisons see:
%
% Groppe, D.M., Urbach, T.P., & Kutas, M. (2011) Mass univariate analysis
% of event-related brain potentials/fields I: A critical tutorial review.
% Psychophysiology, 48(12) pp. 1711-1725, DOI: 10.1111/j.1469-8986.2011.01273.x
% http://www.cogsci.ucsd.edu/~dgroppe/PUBLICATIONS/mass_uni_preprint1.pdf
%
%
% For a review of FCR-adjusted confidence intervals (CIs) and other techniques
% for adjusting CIs for multiple comparisons see:
%
% Groppe, D.M. (in press) Combating the scientific decline effect with
% confidence (intervals). Psychophysiology.
% http://biorxiv.org/content/biorxiv/early/2015/12/10/034074.full.pdf
%
%
% Author:
% David M. Groppe
% Kutaslab
% Dept. of Cognitive Science
% University of California, San Diego
% March 24, 2010
%%%%%%%%%%%%%%%% REVISION LOG %%%%%%%%%%%%%%%%%
%
% 5/7/2010-Added FDR adjusted p-values
% 5/14/2013- D.H.J. Poot, Erasmus MC, improved run-time complexity
% 10/2015- Now returns FCR adjusted confidence intervals
function [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(pvals,q,method,report)
if nargin<1,
error('You need to provide a vector or matrix of p-values.');
else
if ~isempty(find(pvals<0,1)),
error('Some p-values are less than 0.');
elseif ~isempty(find(pvals>1,1)),
error('Some p-values are greater than 1.');
end
end
if nargin<2,
q=.05;
end
if nargin<3,
method='pdep';
end
if nargin<4,
report='no';
end
s=size(pvals);
if (length(s)>2) || s(1)>1,
[p_sorted, sort_ids]=sort(reshape(pvals,1,prod(s)));
else
%p-values are already a row vector
[p_sorted, sort_ids]=sort(pvals);
end
[dummy, unsort_ids]=sort(sort_ids); %indexes to return p_sorted to pvals order
m=length(p_sorted); %number of tests
if strcmpi(method,'pdep'),
%BH procedure for independence or positive dependence
thresh=(1:m)*q/m;
wtd_p=m*p_sorted./(1:m);
elseif strcmpi(method,'dep')
%BH procedure for any dependency structure
denom=m*sum(1./(1:m));
thresh=(1:m)*q/denom;
wtd_p=denom*p_sorted./[1:m];
%Note, it can produce adjusted p-values greater than 1!
%compute adjusted p-values
else
error('Argument ''method'' needs to be ''pdep'' or ''dep''.');
end
if nargout>3,
%compute adjusted p-values; This can be a bit computationally intensive
adj_p=zeros(1,m)*NaN;
[wtd_p_sorted, wtd_p_sindex] = sort( wtd_p );
nextfill = 1;
for k = 1 : m
if wtd_p_sindex(k)>=nextfill
adj_p(nextfill:wtd_p_sindex(k)) = wtd_p_sorted(k);
nextfill = wtd_p_sindex(k)+1;
if nextfill>m
break;
end;
end;
end;
adj_p=reshape(adj_p(unsort_ids),s);
end
rej=p_sorted<=thresh;
max_id=find(rej,1,'last'); %find greatest significant pvalue
if isempty(max_id),
crit_p=0;
h=pvals*0;
adj_ci_cvrg=NaN;
else
crit_p=p_sorted(max_id);
h=pvals<=crit_p;
adj_ci_cvrg=1-thresh(max_id);
end
if strcmpi(report,'yes'),
n_sig=sum(p_sorted<=crit_p);
if n_sig==1,
fprintf('Out of %d tests, %d is significant using a false discovery rate of %f.\n',m,n_sig,q);
else
fprintf('Out of %d tests, %d are significant using a false discovery rate of %f.\n',m,n_sig,q);
end
if strcmpi(method,'pdep'),
fprintf('FDR/FCR procedure used is guaranteed valid for independent or positively dependent tests.\n');
else
fprintf('FDR/FCR procedure used is guaranteed valid for independent or dependent tests.\n');
end
end
|
github
|
philippboehmsturm/antx-master
|
xdeform.m
|
.m
|
antx-master/mritools/ant/xdeform.m
| 2,270 |
utf_8
|
1b47b324c8342dfce3f6d32a71198bd3
|
function testdeform( files ,direction, resolution, interpx)
if exist('direction')~=1; direction=[]; end;
if isempty(direction); direction =1; end
if exist('resolution')~=1; resolution=[]; end;
if isempty(resolution); resolution =[.025 .025 .025]; end
if exist('interpx')~=1; interpx=[]; end;
if isempty(interpx); interpx =4; end
pathx=fileparts(files{1});
% bbox = [-6 -9.5 -7
% 6 5.5 1];
cnt = 1;
nr = 1;
if direction==1
matlabbatch{cnt}.spm.util.defs.comp{1}.def = {fullfile(pathx,'y_forward.nii')};
bbox = world_bb(fullfile(pathx,'y_forward.nii'));
elseif direction==-1
matlabbatch{cnt}.spm.util.defs.comp{1}.def = {fullfile(pathx,'y_inverse.nii')};
bbox = world_bb(fullfile(pathx,'y_inverse.nii'));
end
%matlabbatch{cnt}.spm.util.defs.comp{2}.id.space = '<UNDEFINED>'; % For fMRI Files use fMRI-Scan resolution.
matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.vox = resolution;
matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.bb = bbox;
matlabbatch{cnt}.spm.util.defs.ofname = '';
matlabbatch{cnt}.spm.util.defs.fnames = files(1:end);
matlabbatch{cnt}.spm.util.defs.savedir.savesrc = 1;
matlabbatch{cnt}.spm.util.defs.interp =interpx;% 4; default is 4 (spline4)
spm_jobman('serial', matlabbatch);
% resolution =[.025 .025 .025]
% bbox = [-6 -9.5 -7
% 6 5.5 1];
% cnt = 1;
% nr = 1;
% AMAfiles =..
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\t2_1.nii,1'
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\c1t2_1.nii,1'
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\c2t2_1.nii,1'
% % 'C:\Users\skoch\Desktop\SPMmouseBerlin\mouse001\c1c2mask.nii,1'
% %
% matlabbatch{cnt}.spm.util.defs.comp{1}.def = {fullfile(t2destpath,'y_forward.nii')};
% %matlabbatch{cnt}.spm.util.defs.comp{2}.id.space = '<UNDEFINED>'; % For fMRI Files use fMRI-Scan resolution.
% matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.vox = resolution;
% matlabbatch{cnt}.spm.util.defs.comp{2}.idbbvox.bb = bbox;
% matlabbatch{cnt}.spm.util.defs.ofname = '';
% matlabbatch{cnt}.spm.util.defs.fnames = AMAfiles(1:end);
% matlabbatch{cnt}.spm.util.defs.savedir.savesrc = 1;
% matlabbatch{cnt}.spm.util.defs.interp = 4;
% spm_jobman('serial', matlabbatch);
|
github
|
philippboehmsturm/antx-master
|
fn_structdisp.m
|
.m
|
antx-master/mritools/ant/fn_structdisp.m
| 2,914 |
utf_8
|
e11c66742f7b48aaae1ca3d478b79905
|
function s=fn_structdisp(Xname)
% function fn_structdisp Xname
% function fn_structdisp(X)
%---
% Recursively display the content of a structure and its sub-structures
%
% Input:
% - Xname/X one can give as argument either the structure to display or
% or a string (the name in the current workspace of the
% structure to display)
%
% A few parameters can be adjusted inside the m file to determine when
% arrays and cell should be displayed completely or not
% Thomas Deneux
% Copyright 2005-2012
s=[];
% diary muell9999123.txt;
diary(fullfile(pwd,'muell9999123.txt'));
if ischar(Xname)
X = evalin('caller',Xname);
else
X = Xname;
Xname = inputname(1);
end
if ~isstruct(X), error('argument should be a structure or the name of a structure'), end
rec_structdisp(Xname,X);
diary off;
s=tovar;
function s=tovar
fid=fopen('muell9999123.txt','r');
s = {};
tline = fgetl(fid);
while ischar(tline)
disp(tline)
tline = fgetl(fid);
s{end+1,1}=tline;
end
fclose(fid);
s(end)=[];
delete('muell9999123.txt');
%---------------------------------
function rec_structdisp(Xname,X)
%---
%-- PARAMETERS (Edit this) --%
ARRAYMAXROWS = 20;
ARRAYMAXCOLS = 20;
ARRAYMAXELEMS = 300;
CELLMAXROWS = 20;
CELLMAXCOLS = 20;
CELLMAXELEMS = 300;
CELLRECURSIVE = true;
%----- PARAMETERS END -------%
disp([Xname ':'])
disp(X)
%fprintf('\b')
if isstruct(X) || isobject(X)
F = fieldnames(X);
nsub = length(F);
Y = cell(1,nsub);
subnames = cell(1,nsub);
for i=1:nsub
f = F{i};
Y{i} = X.(f);
subnames{i} = [Xname '.' f];
end
elseif CELLRECURSIVE && iscell(X)
nsub = numel(X);
s = size(X);
Y = X(:);
subnames = cell(1,nsub);
for i=1:nsub
inds = s;
globind = i-1;
for k=1:length(s)
inds(k) = 1+mod(globind,s(k));
globind = floor(globind/s(k));
end
subnames{i} = [Xname '{' num2str(inds,'%i,')];
subnames{i}(end) = '}';
end
else
return
end
for i=1:nsub
a = Y{i};
if isstruct(a) || isobject(a)
if length(a)==1
rec_structdisp(subnames{i},a)
else
for k=1:length(a)
rec_structdisp([subnames{i} '(' num2str(k) ')'],a(k))
end
end
elseif iscell(a)
if size(a,1)<=CELLMAXROWS && size(a,2)<=CELLMAXCOLS && numel(a)<=CELLMAXELEMS
rec_structdisp(subnames{i},a)
end
elseif size(a,1)<=ARRAYMAXROWS && size(a,2)<=ARRAYMAXCOLS && numel(a)<=ARRAYMAXELEMS
try
try
disp([subnames{i} ': ' a]);
catch
disp([subnames{i} ': ' num2str(a)]);
end
catch
disp([subnames{i} ': ']);
disp(a);
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.