Download images automatically
Question: I have written this piece of python code which downloads a number of images
from a repository of images and saves them in specified folder. The code looks
like this:

    
    
    import urllib.request
    import cv2
    import numpy as np
    import os
    
    def store_raw_images():
        neg_images_link = 'http://image-  net.org/api/text/imagenet.synset.geturls?wnid=n00464651'
        neg_images_urls =  urllib.request.urlopen(neg_images_link).read().decode()
    
        if not os.path.exists('neg'):
           os.makedirs('neg')
    
        pic_num = 1
        for i in neg_images_urls.split('\n'):
            try:
                print(i)
                urllib.request.urlretrieve(i, "neg/{}.jpg".format(pic_num))
                img = cv2.imread("neg/{}.jpg".format(pic_num) + cv2.IMREAD_GRAYSCALE)
                resized_image = cv2.resize(img, (100, 100))
                cv2.imwrite("neg/{}.jpg".format(pic_num), resized_image)
                pic_num = pic_num + 1
                print(pic_num)
    
            except Exception as e:
                print(str(e))
    
    store_raw_images()
    

For some reason the images are replaced and I do NOT see all images. I keep
seeing one image `1.jpg` and all the images seem to replaced, though I expect
the name of the images to go `1.jpg`, `2.jpg` , ... .

I also see this warning/error but I am not sure if it is relevant to this
problem or not.

    
    
    Can't convert 'int' object to str   
    http://www.azjeugd.nl/site/modules/xcgal/albums/20082009seizoen/a1/groningen_thuis/IMG_7798.jpg
      HTTP Error 403: Forbidden
      http://www.ga-eagles.nl/images/duels1e0809/gaetel6.jpg
    

Where do you think the problem lies?

Note that I am incrementing the image number:

    
    
            pic_num = pic_num + 1
    


Answer: You have everything in one `try/except` block. Assuming `cv2.imwrite` fails
but all the other lines are executed without any problems, your code will
never reach `picnum = picnum + 1`. Try rearranging your code where you first
increase `picnum` and check which lines actually gives you the error.

