Skip to content

Instantly share code, notes, and snippets.

@chris-taylor
Created April 30, 2013 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-taylor/5487589 to your computer and use it in GitHub Desktop.
Save chris-taylor/5487589 to your computer and use it in GitHub Desktop.
Download images from Google image search
function search(query,path)
% Download full size images from Google image search. Saves image files
% locally. Do not print or republish images without permission.
%
% Based on Python code by Craig Quiter at https://gist.github.com/crizCraig/2816295
%
% Requires the JSONLab package, available from
% http://www.mathworks.com/matlabcentral/fileexchange/33381-jsonlab-a-toolbox-to-encodedecode-json-files-in-matlaboctave
%
% USAGE
% >> search('dog')
% >> search('landscape')
%
error(nargchk(1,2,nargin));
if nargin < 2, path = ''; end
baseurl = ['https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' query '&start=%d'];
baseurl = strrep(baseurl, ' ', '%%20');
basepath = fullfile(path,query);
if ~exist(basepath,'dir')
mkdir(basepath)
end
start = 0;
while start < 60 % Google will only return a max of 60 results
json = loadjson(urlread(sprintf(baseurl,start)));
for ii = 1:length(json.responseData.results)
imageinfo = json.responseData.results(ii);
url = imageinfo.unescapedUrl;
try
image = imread(url);
catch %#ok
fprintf('Could not download %s\n',url);
continue
end
try
imwrite(image, fullfile(basepath, sprintf('%s%02d.jpg',query,start+ii)));
catch %#ok
fprintf('Could not save %s\n', url);
continue
end
end
disp(start)
start = start + 4; % 4 images per page
% be nice to Google!
pause(1.5)
end
end
@geekyfranzy
Copy link

I want to search with image(upload image) instead of string. Please give me some advices.

@omrysendik
Copy link

This doesn't work anymore because the ajax google API is deprecated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment