MATLAB: cropping all images in a folder with different coordinates - matlab

i use the following MATLAB code to crop all images in a folder, it works perfectly but the problem is that it crops all the images with the same coordinates, what i want is to crop each image with specific coordinate. the coordinates of the images exist in a table in order, for example the coordinates of the image 1 are in row 1 and so on.
here is the code to get the coordinates in a table:
filename = 'fich.txt';
fid = fopen(filename);
A = textscan(fid, '%*s%*s%*s%*s%f%f%*f');
res = cell2mat(A);
res(isnan(res))=300;% remplacer les valeurs "NAN" dans la matrice par la valeur 300
fclose(fid);
and here is the code that cropps all images with the same coordinates:
% operating all pictures in a folder
clear all
close all
clc
dname_open = ('myfold') ; %Default Directory To be Opened
dname_save = ('myfold-cropped') ;
test = 0 ; % 0 - does every file in folder, 1 - only does first file
%% Set up basic file name path to read
top_file= [dname_open '\'] ; %Set up main database to open and look inside
ls_top_file = ls(top_file) ; %List Files inside main folder
c = cellstr(ls_top_file) ; %Turn cells from ls function into strings
cc = c(3:length(c)) ; %Set up a matrix without the . and .. produces by the ls function
S = size(cc) ; %Find the size of matrix containing names of files inside of main database
a = 1 ; %This counter is set to 3 to account for the . and .. at the beggining of each matrix created by ls
S(1)
while a <= S(1)
close all
file = char(cellstr([top_file char(cc(a))])) ; %File to be operated on
data_n = char(cc(a))
file_name = char(cc(a)) ;
% Operations on files in folder
imagename = (file_name) ;
%Input image image
fileToRead2 = [dname_open '\' imagename] ;
I = imread(fileToRead2);
%I2 = imcrop(I, rect) crops the image I. rect is a four-element position
%vector[xmin ymin width height] that specifies the size and position of the crop rectangle.
I2 = imcrop(I,[189.5 1.5 588 1022]);
imshow(I2,'Border','tight')
set(gcf, 'PaperPositionMode', 'auto');
h = gcf ;
saveas(h, [dname_save '\' 'z_' imagename ], 'pgm');
if test == 1
fprintf('breaking loop to set axis - test==1')
break
end
a = a+1 ;
end
thank you

Related

Matlab - Multiple Plots in one Figure

I have a question about plots and subplots. I am iterating over some data and I am trying to get everything into a plot. It worked that every plot got written into one plot with hold on and figure but now I have to fit in regression lines. Therefore I want to plot everythiong into one figure but into different plots. This doesnt work as my plot looks a little bit weird.
My problem now is, that I cant find real helpful things on how to manage those plots other than using uicontrol. But I have never ever used uicontrol and I can´t find enogh documentation to use it properly. I found this code:
figure(1)
panel1 = uipanel('Parent',1);
panel2 = uipanel('Parent',panel1);
set(panel1,'Position',[0 0 .99 1]);
set(panel2,'Position',[-1 0 2 1]);
set(gca,'Parent',panel2);
h = image; % <- Code for my own image goes here
s = uicontrol('Style','Slider','Parent',1,...
'Units','normalized','Position',[0 0 1 .025],...
'Value',1,'Callback',{#slider_callback1,panel2});
but all I get is a callback Problem. I dont know how to switch from a horizontal to a vertikal scrollbar and how to get my plots in there. The code manage it to write into the figure but in a very strange way that results in a similiar way as the subplotting everything.
I hope you can help me as good as always!
PS: This is my current code thats working (picture of the plot after it)
%% Clear Workspace
clc, clear all, close all; %
S = {} ;
F = [] ;
figure, hold on ;
%% Specify working directory
myFolder = '/home/k/karkarov92/Documents/Daten Igor/Zwick';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
%% Start Import from Mathilda aka. Z20
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.TXT'); % Change to whatever pattern needed.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
str = baseFileName;
level = wildcardPattern + "NIE_TOM_1_" ; % Name of the Pattern before the Name of the Sample
pat = asManyOfPattern(level);
str = extractAfter(str,pat);
Sample = erase(str,".TXT");
disp(Sample)
delimiterIn = ' '; %Extract thickness out of headers
headerlinesIn = 9;
G = importdata(fullFileName,delimiterIn,headerlinesIn);
G(3);
H = split(G(3));
K = H(2);
thickness = str2double(K)/100 ;
%read Table and extract Units
A = readtable(fullFileName,'decimal', ','); % without decimal and "," data import not with the right value wrong unit
Units = A(1,:);
A(1,:) = []; %units extracted and then stripped from table
%table = A(1:4,:); table output test
B = table2array(A); %change data from table to array
%disp(B(1:4,:)) ; %Array output test
strain = (B(:,2)- B(1,2)) / B(1,2); %strain calculated and stored in vector strain
stretch = strain +1 ; %stretch calculated and stored in vector strain
crossSection = 5. * thickness ; %calculate cauchy stress and cross section
cauchyStress = ((B(1:end,3).*stretch) / crossSection ) * 1000 ; %[GPa]
M = max(B) ; %exctract maxForce
maxForce = M(1,3) ;
F(end+1) = maxForce ;
S{k} = Sample ;
plot(stretch,cauchyStress)
xlabel('Stretch')
ylabel('Cauchy Stress')
title('Linear Regression for Modulus')
grid on
end

how to detect partial corrupted images in Jpg/Jpeg format

In a very big image dataset, we have some corrupted images as following images. These images can be viewed without any problem, but human eyes can see some corrupted areas in gray color. How can I detect these corrupted images?
Actually I have written a script in Matlab for detecting. It could filter most of the corrupted images, but some will be miss. The main idea of my script is find common binary string of corrupted images. While some corrupted images don't obtain this common binary string. So they will not be filtered.
My Matlab code:
FOLDER1 = './'; % query data
query_folder1 = FOLDER1;
query_pt1 = dir(strcat(query_folder1, '*.jpg'));
nFile1 = length(query_pt1); % file number
BROKEN_MARK = '00455114';
SIZE = 4; % single size
THRESH = 3;
for i = 1:nFile1
img_dir = strcat(FOLDER1, query_pt1(i).name());
fid = fopen(img_dir);
im1_stats = dir(img_dir);
file_length = im1_stats.bytes;
pos = -4;
epost = -200;
count = 0;
while abs(pos) <= ceil(file_length)
fseek(fid, pos, 'eof');
temp = fread(fid, 1, 'single');
str = num2hex(single(temp));
if(strcmp(str, BROKEN_MARK))
%fprintf('%s\n', img_dir);
if(count >= THRESH)
copyfile(img_dir, 'candidates/');
break;
else
count = count + 1;
end
else
count = 0;
pos = pos - 1;
end
end
fclose(fid);
end
Could any one give some idea for detecting all corrupted images? Or any Python, C++, Matlab or bash script code. Thank you.
They are not technically corrupted if you can view them. They are "corrupted" in your perception. Personally I would count all gray pixels and if the percentage is greater than a given amount the image is considered "corrupted", checked manually and deleted.
#!/usr/bin/python
# -*- coding: utf-8 -*-
persantage=10 # Corrupted area in per cent to detect
color=(128, 128, 128) # Corruption color, tuple
from PIL import Image
im = Image.open("corrupted.jpg")
pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
gray=0
other=0
for data in pixels:
for pix in data:
if pix == color:
gray += 1
else:
other += 1
corruption_area= gray *100 / (gray+other)
if corruption_area >= persantage:
print 'Corruption:', corruption_area, '%'
else:
print 'OK'
Output for the attached image below is
Corruption: 18 %
I used already detected corrupted images for analyzing corrupted parts. Then use these results to detect possible corruption. Here is Matlab code:
clear; clc;
FOLDER1 = './';
query_folder1 = FOLDER1; % Some corrupted samples are here.
query_pt1 = dir(strcat(query_folder1, '*.jpg'));
nFile1 = length(query_pt1); % file number
OFF = 10;
for i = 1:nFile1
img_dir = strcat(FOLDER1, query_pt1(i).name());
img = imread(img_dir);
[x y ~] = size(img);
img_part = img(x-OFF:x, y-OFF:y, :); % Get samples from right-bottom corner
hist(i, :) = rgbhist_fast(img_part, 4); % get RGB histogram of sample part of corrupted region
end
mean_hist = mean(hist); % Use average of RGB histogram of samples for standard of corruption
FOLDER2 = '~/data/logo_data/930k_iautocrop/'; % Main big dataset
query_folder2 = FOLDER2;
query_pt2 = dir(strcat(query_folder2, '*.jpg'));
nFile2 = length(query_pt2); % file number
for i = 1:nFile2
if(mod(i, 100) == 0)
fprintf('%d\n', i);
end
img_dir = strcat(FOLDER2, query_pt2(i).name());
img = imread(img_dir);
[x y ~] = size(img);
img_part = img(x-OFF:x, y-OFF:y, :);
temp_hist = rgbhist_fast(img_part, 4);
dist(i) = sqrt(sum((mean_hist - temp_hist').^2, 2)); % get corrupted similarity
%imshow(img_part);
end
[v ix] = sort(dist, 'ascend'); % To find most corrupted images. The images on the top of the list have high corruption probability

Matlab - How can I write the values to an excel in a nested for loop

I have an Image which is 1944(R) x 2592 (C). I would like to take one column at a time; treating each column as an Image and calculate how many pixels among each row of that column contains value > half(max) value of that column. Those number of pixels are to be written to the excel sheet corresponding to it's respective column.
Image: the image
Here is what I have tried so far, I am not able to write it successfully.
clc;
sig = rgb2gray(imread('1.bmp')); % read in the image.
% imshow(sig);
ArraySize = size(sig); %1944(R) x 2592 (C)
[maxval, maxloc] = max(sig(:)); % Gives the max and the location
maxval; % max value
[maxloc_row, maxloc_col] = ind2sub(size(sig), maxloc); % convert logical
%-------------------------------------------------------------------%
% Count pixels through each column > half(max) value of that column
%-------------------------------------------------------------------%
newfilename = 'Results.csv'; % write new values to .csv files
Array = zeros(2592,2);
% % R = Array(:,1);
% y = Array(:,2);
for a = 1: 2592% maxloc_row = 635 maxloc_col = 1094
[a_maxval, a_maxloc] = max(sig(:,a)); % search max among every column.
% maxloc is the row at which maxval is.
newval = a_maxval/2; % averaged max value
% New structure for find width
x = 0;
x = Array(:, 1);
for b = 1: 1944 % maxloc_row = 635 maxloc_col = 1094
% R = b;
if sig(b,a) > newval
x=x+1;
end
end % End row search
x;
% y = x*(2.2); % pixels into microns
output = [num2cell(x)];
xlswrite(newfilename, output);
end % End column search
I think csvwrite can write data to csv file. Here's what you can try:
place output = []; somewhrere at top, says below clc;
then, replace
output = [num2cell(x)]; with output = [output x];
and
xlswrite(newfilename, output); with csvwrite(newfilename, output); but place it at the end of program because output has all x inside.
I have tried and it works.

Running matlab code through a folder

I have the following code for which instead of loading one image at a time, I'd like to run through every image in a folder (the defective folder in this code). I'd like the output to be an array containing the values of 'G' for each of the input images. I'm not too sure how to go about this - so any points appreciated. Many thanks!
%PCA code,
img = imread('C:\users\m7-miller\desktop\250images\defective\inkblob01.png');
img_gray = rgb2gray(img);
img_gray_double = im2double(img_gray);
figure,
set(gcf,'numbertitle','off','name','Grayscale Image'),
imshow(img_gray_double)
%find mean of the image
img_mean = mean(img_gray_double);
[m n] = size(img_gray);
%Make column vector of mean image value
new_mean = repmat(img_mean,m,1);
%Mean corrected image
Corrected_img = img_gray_double - new_mean;
%Covariance matrix of corrected image
cov_img = cov(Corrected_img);
%Eigenvalues of covariance matrix - columns of V are e-vectors,
%diagonals of D e-values
[V, D] = eig(cov_img);
V_T = transpose(V);
Corrected_image_T = transpose(Corrected_img);
FinalData = V_T * Corrected_image_T;
% Image approximation by choosing only a selection of principal components
PCs = 3;
PCs = n - PCs;
Reduced_V = V;
for i = 1:PCs,
Reduced_V(:,1) =[];
end
Y=Reduced_V'* Corrected_image_T;
Compressed_img = Reduced_V*Y;
Compressed_img = Compressed_img' + new_mean;
figure,
set(gcf,'numbertitle','off','name','Compressed Image'),
imshow(Compressed_img)
% End of image compression
% Difference of original image and compressed
S = (img_gray_double - Compressed_img);
figure,
set(gcf,'numbertitle','off','name','Difference'),
imshow(S)
% Sum of the differences
F = sum(S);
G = sum(F)
Are you looking for the dir command?
files = dir('*.png');
for n=1:size(files,1)
filename = files(n).name;
img = imread(filename);
....
G = sum(F);
end

How to place an image A onto image B BUT I WANT TO IGNORE all O pixels of image A

I want to place a modelImage (RGB image) on baseImage (RGB image) where the center of modelImage will be placed at pPoint.
I already wrote the function.
And it works. However, there are some 0 pixels in the modelImage. I do not want to place 0 pixels of modelImage onto baseImage. Can you help me to modify my function?
% Put the modelImage onto baseImage at pPoint
function newImage = imgTranslate(modelImage,baseImage, pPoint)
[nRow nCol noDim] = size(modelImage);
pPointX = pPoint(1);
pPointY = pPoint(2);
startColumn = pPointY - nCol/2;
startRow = pPointX - nRow/2;
startColumn = round(startColumn);
startRow = round(startRow);
endColumn = startColumn+ nCol;
endRow = startRow+nRow;
%% Place modelImage onto baseImage BUT I WANT TO IGNORE O pixels of modelImage
baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:) = modelImage;
newImage = baseImage;
Using FOR and IF works but it will slow the progam
%%
for i = startRow: (endRow-1)
x = (i-startRow +1);
for j = startColumn : (endColumn-1)
y = j-startColumn + 1;
if modelImage(x,y,:)~=0
baseImage(i,j,:) = modelImage(x,y,:);
end
end
end
Any way to not to use FOR and IF ?
There may be a way to simplify this, but something like (untested):
% Indicator map of non-zeros
nzs = any(modelImage,3);
nzs = repmat(nzs, [1 1 3]);
% Crop destination image
tmpImage = baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:);
% Replace all but non-zeros
tmpImage(nzs) = modelImage(nzs);
% Place into output image as before
baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:) = tmpImage;
% Indicator map of non-zeros
zs = modelImage(:,:,:)==0;
nzs = ~zs;
% Crop destination image
tmpImage = baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:);
% Replace all but non-zeros
tmpImage(nzs) = modelImage(nzs);
% Place into output image as before
baseImage(startRow:(endRow-1),startColumn:(endColumn-1),:) = tmpImage;