RMarkdown reformatting base r plot - image

I'm building an r package and trying to include a plot in my package vignette. Here is the code in my vignette (with options echo=F,warnings=F):
summary_table = data.frame(n_row = rep(seq(100,1000,100),each = 2),mean = c(0.087,0.137,0.278,1.880,0.859,8.742,1.782,28.908,3.928,63.544,6.648,141.373,11.158,252.689,18.409,427.515,28.220,725.520,39.675,1024.007),sd = c(0.021,0.010,0.018,0.170,0.100,0.630,0.161,1.849,0.245,3.927,0.455,12.202,0.806,14.315,1.350,37.318,2.675,63.963,2.983,102.328),package = rep(c("TDAInference","TDA"),10))
# plot table
plot(summary_table$n_row[summary_table$package=="TDA"], summary_table$mean[summary_table$package=="TDA"], type="b",
xlim=range(summary_table$n_row), ylim=range(0,summary_table$mean+1.96*summary_table$sd),xlab = "Points in diagram",ylab = "Mean execution time (sec)",main = "Benchmarking diagram_distance function")
lines(summary_table$n_row[summary_table$package=="TDAInference"], summary_table$mean[summary_table$package=="TDAInference"], col=2, type="b")
legend(x = 200,y = 800,legend = c("TDAInference","TDA"),col = c("red","black"),lty = c(1,1),cex = 0.8)
arrows(summary_table$n_row, summary_table$mean-1.96*summary_table$sd/sqrt(10), summary_table$n_row, summary_table$mean+1.96*summary_table$sd/sqrt(10), length=0.05, angle=90, code=3)
When I run the code chunk in my script it looks like this, Desired plot, which is what I want. However, when I use devtools::build_vignettes() and view the vignette it looks like this: Reformatted plot
Any idea why this is happening and how I could fix the problem?

Related

open3d voxel_size too small : down sampling not working for e57 binaries

I'm trying to downsample a point cloud. I have 2 data formats for different parts of my data.
The .bin files cause no problems, but when I'm trying to downsample the .e57 files I encounter a strange problem.
Here's what I do:
import numpy as np
import open3d
pointfile = "path/to/file.e57"
pcd_data = np.fromfile(point_file, dtype=np.float32)
pcd_data = velo_data.reshape(-1, 4)
pcd_points = velo_data[:, :3]
pcd = open3d.geometry.PointCloud()
pcd.points = open3d.utility.Vector3dVector(pcd_points)
pcd_down = pcd.voxel_down_sample(voxel_size=0.8)
res = np.asarray(pcd_down.points)
It works fine for .bin, but when i try the .e57 I get the error:
RuntimeError: [Open3D ERROR] [VoxelDownSample] voxel_size is too small.
No matter if I use voxel_size of 0.005, 0.8, 100, 5000 or 1000000000000000.
I tried the earlier open3d Version:
pcd_down = open3d.geometry.voxel_down_sample(voxel_size=0.8)
and at least it throws no error, but my downsampled pointcloud then contains 0 points (from ~350 000).
As the file should be structured in points with 4 features, the file seems to be read correctly (this works for any of my files), as the reshape works just fine.
Any ideas?
Still have no clue about the original error, but I succesfully worked around the problem by using pye57:
https://github.com/davidcaron/pye57
together with this solution to a possibly occuring problem:
https://github.com/davidcaron/pye57/issues/6#issuecomment-803894677
With this code
import numpy as np
import open3d
import pye57
point_file = "path/to/file.e57"
e57 = pye57.E57(point_file)
data = e57.read_scan_raw(0)
assert isinstance(data["cartesianX"], np.ndarray)
assert isinstance(data["cartesianY"], np.ndarray)
assert isinstance(data["cartesianZ"], np.ndarray)
x = np.array(data["cartesianX"])
y = np.array(data["cartesianY"])
z = np.array(data["cartesianZ"])
pcd_points = np.concatenate((x, y), axis=0)
pcd_points = np.concatenate((pcd_points, z), axis=0)
pcd_points = velo_points.reshape(-1, 3)
pcd = open3d.geometry.PointCloud()
pcd.points = open3d.utility.Vector3dVector(pcd_points)
pcd_down = pcd.voxel_down_sample(voxel_size=0.0035)
I finally get a downsampled point cloud.

Image registration with SimpleITK

I want to do multi-modality image registration(mri/ct) but I do not have completely aligned images, results obtained with simpleITK are very bad. Even if I try to align them, results are still ridiculously bad.
What can I do to fix this? My registration code is as follow:
import SimpleITK as sitk
def fusion(ct, mr):
fixed = sitk.GetImageFromArray(ct, isVector=True)
moving = sitk.GetImageFromArray(mr, isVector=True)
numberOfBins = 24
samplingPercentage = 0.10
R = sitk.ImageRegistrationMethod()
R.SetMetricAsMattesMutualInformation(numberOfBins)
R.SetMetricSamplingPercentage(samplingPercentage,sitk.sitkWallClock)
R.SetMetricSamplingStrategy(R.RANDOM)
R.SetOptimizerAsRegularStepGradientDescent(1.0,.001,200)
R.SetInitialTransform(sitk.TranslationTransform(fixed.GetDimension()))
R.SetInterpolator(sitk.sitkLinear)
#R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
outTx = R.Execute(fixed, moving)
def get_result():
resampler = sitk.ResampleImageFilter()
resampler.SetReferenceImage(fixed);
resampler.SetInterpolator(sitk.sitkLinear)
resampler.SetDefaultPixelValue(100)
resampler.SetTransform(outTx)
out = resampler.Execute(moving)
simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
return sitk.GetArrayFromImage(cimg)
#sitk.Show( cimg, "ImageRegi
return get_result()
I think you forgot to make an initial alignment of your images at the beginning.
trans = sitk.CenteredTransformInitializer(fixed ,moving, sitk.Euler3DTransform(), sitk.CenteredTransformInitializerFilter.GEOMETRY)

I m new to Matlab and currently working of weapon detection in images but i m getting false positives here.What should i do?

How can i caluclate the F1 score using matlab .This code is giving positive results in negative samples also .I think thats because of dynamic background of images in datset. Should i change the dataset for better accuracy or change the approach .Please Help
Thanks
DataSet : http://kt.agh.edu.pl/~matiolanski/KnivesImagesDatabase/KnivesImagesDatabase.rar
CODE:`
TrainingSet = imageSet('Trainingset','recursive');
testSet= imageSet('TestSet','recursive');
img=read(TrainingSet(1),1);
[hog_4x4, vis4x4] = extractHOGFeatures(img,'CellSize',[4 4]);
cellSize = [4 4];
hogFeatureSize = length(hog_4x4);
trainingFeatures= [];
trainingLabels = [];
x= TrainingSet(1).Count;
y= TrainingSet(2).Count;
for digit = 1:numel(TrainingSet)-1
numImages = TrainingSet(digit).Count;
for i = 1:numImages-1
img = rgb2gray(read(TrainingSet(digit), i));
%Apply pre-processing steps
features(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);
end
%labels = repmat(TrainingSet(digit).Description, numImages, 1);
trainingFeatures = [trainingFeatures; features];
%trainingLabels = [trainingLabels; labels ];
end
negativeSize = size(trainingFeatures,1);
trainingLabels = zeros(size(trainingFeatures,1),1);
for digit = 2:2
numImages= TrainingSet(digit).Count;
for i = 1:numImages-1
img = rgb2gray(read(TrainingSet(digit), (i)));
features1(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);
end
%labels = repmat(TrainingSet(digit).Description, numImages, 1);
trainingFeatures = [trainingFeatures; features1];
%trainingLabels = [trainingLabels; labels ];
end
positiveLabels = ones(size(trainingFeatures,1) - negativeSize,1);
trainingLabels = [trainingLabels ; positiveLabels];
classifier = fitcsvm(trainingFeatures, trainingLabels);
classOrder =classifier.ClassNames;
img=read(testSet(1),1);
img = rgb2gray(img);
[testFeatures, testLabels] = extractHOGFeatures(img, 'CellSize', cellSize);
%Make class predictions using the test features.
predictedLabels = predict(classifier, testFeatures);
if(predictedLabels==1)
warndlg('Object Detected','!! Warning !!');
else
warndlg('Object Not Detected','!! Warning !!');
end
I strongly recommend using Faster-rcnn for the problem. It is one of the state-of-the art Convolutional Neural Network architectures used extensively for object detection task. Here is a matlab implementation of the same.

Reverse image search implementation

I am currently trying to make a site which will contain several images with patterns and shapes (Lets say few squares and circles of various colors and shape in each picture). And I am aiming to provide the user a way to upload their images of the pattern and do a reverse image search to check whether similar pattern image already exists in my site or not. So is there any way to implement the same, either by custom code or by using any third party api/widgets etc?
Hi Ashish below is a matlab code for a function which generates signature of a particular binary object's surface, which is nearly size dependent, you can use this concept for matching a shape on different scale.
function sig = signature(bw,prec)
boundry = bwboundaries(bw);
xy = boundry{1};
x = xy(:,1);
y = xy(:,2);
len = length(x);
res = (len/prec);
re = rem(res,2);
if re
res = ceil(res);
end
indexes = 1:res:len;
xnew = x(indexes);
ynew = y(indexes);
cx = round(mean(xnew));
cy = round(mean(ynew));
xn = abs(xnew-cx);
yn = abs(ynew-cy);
sig = (xn.^2+yn.^2);
sig = sig/max(sig);
Following is the example of how to use signature function:
clc
clear all
close all
path = 'E:\GoogleDrive\Mathworks\irisDEt\shapes';
im1 = imread([path,'\3.png']);
gray1 = ((im1));
scales = [1,2,3,4];
gray1 = im2bw(gray1);
for i = 1:length(scales)
im = imresize(gray1,scales(i));
sig = signature(im,25);
figure,plot(sig)
fra = getframe();
image = frame2im(fra);
imwrite(image,['E:\GoogleDrive\Mathworks\irisDEt\shapes\',num2str(i),'.png'])
end
following is the test image and its signature for changing in size od images which looks similar in shape.
All above signatures are generated by the code given above.

Figure window showing up matlab

I have written this code to help me compare different image histograms however when i run it i get a figure window popping up. I can't see anywhere in the code where i have written imshow and am really confused. Can anyone see why? thanks
%ensure we start with an empty workspace
clear
myPath= 'C:\coursework\'; %#'
number_of_desired_results = 5; %top n results to return
images_path = strcat(myPath, 'fruitnveg');
images_file_names = dir(fullfile(images_path, '*.png'));
images = cell(length(images_file_names), 3);
number_of_images = length(images);
%textures contruction
%loop through all textures and store them
disp('Starting construction of search domain...');
for i = 1:length(images)
image = strcat(images_path, '\', images_file_names(i).name); %#'
%store image object of image
images{i, 1} = imread(image);
%store histogram of image
images{i, 2} = imhist(rgb2ind(images{i, 1}, colormap(colorcube(256))));
%store name of image
images{i, 3} = images_file_names(i).name;
disp(strcat({'Loaded image '}, num2str(i)));
end
disp('Construction of search domain done');
%load the three example images
RGB1 = imread('C:\coursework\examples\salmon.jpg');
X1 = rgb2ind(RGB1,colormap(colorcube(256)));
example1 = imhist(X1);
RGB2 = imread('C:\coursework\examples\eggs.jpg');
X2 = rgb2ind(RGB2,colormap(colorcube(256)));
example2 = imhist(X2);
RGB3 = imread('C:\coursework\examples\steak.jpg');
X3 = rgb2ind(RGB3,colormap(colorcube(256)));
example3 = imhist(X3);
disp('three examples loaded');
disp('compare examples to loaded fruit images');
results = cell(length(images), 2);
results2 = cell(length(images), 2);
results3 = cell(length(images), 2);
for i = 1:length(images)
results{i,1} = images{i,3};
results{i,2} = hi(example1,images{i, 2});
end
results = flipdim(sortrows(results,2),1);
for i = 1:length(images)
results2{i,1} = images{i,3};
results2{i,2} = hi(example2,images{i, 2});
end
results2 = flipdim(sortrows(results2,2),1);
for i = 1:length(images)
results3{i,1} = images{i,3};
results3{i,2} = hi(example3,images{i, 2});
end
results3 = flipdim(sortrows(results3,2),1);
The colormap function sets the current figure's colormap, if there is no figure one is created.
The second parameter of imhist should be the number of bins used in the histogram, not the colormap.
Run your code in the Matlab debugger, step through it line by line, and see when the figure window pops up. That'll tell you what's creating it.
Etienne's answer is right for why you're getting a figure, but I'd just like to add that colormap is unnecessary in this code:
images{i, 2} = imhist(rgb2ind(images{i, 1}, colormap(colorcube(256))));
All you need is:
images{i, 2} = imhist(rgb2ind(images{i, 1}, colorcube(256)));
The second input of rgb2ind should be a colormap, yes. But the output of colorcube is a colormap already. Unless you've got an existing figure and you either want to set the colormap of it or retrieve the colormap it is currently using, the actual function colormap is not necessary.
Other than opening an unnecessary figure, the output of your existing code won't be wrong, as I think in this situation colormap will just pass as an output argument the colormap it was given as an input argument. For example, if you want to set the current figure colormap to one of the inbuilts and return the actual colormap:
cmap = colormap('bone');

Resources