Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用urllib下载图像_Python_Opencv_Python 3.4 - Fatal编程技术网

Python 使用urllib下载图像

Python 使用urllib下载图像,python,opencv,python-3.4,Python,Opencv,Python 3.4,我正在尝试运行此代码。但它不起作用,它的想法是访问带有图像url的文件,访问这些图像,调整图像大小并保存图像。我正在使用Python 3.4、opencv 3.0和Visual Studio。欢迎任何帮助 import urllib.request import cv2 import numpy as np import os def store_raw_images(): neg_images_link = 'http://image- net.org/api/te

我正在尝试运行此代码。但它不起作用,它的想法是访问带有图像url的文件,访问这些图像,调整图像大小并保存图像。我正在使用Python 3.4、opencv 3.0和Visual Studio。欢迎任何帮助

 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=n07942152'   
     neg_image_urls = urllib.request.urlopen(neg_images_link).read().decode()
     pic_num = 1

    if not os.path.exists('neg'):
        os.makedirs('neg')

   for i in neg_image_urls.split('\n'):
    try:
        print(i)
        urllib.request.urlretrieve(i, "neg/"+str(pic_num)+".jpg")
        img = cv2.imread("neg/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
        # should be larger than samples / pos pic (so we can place our image on it)
        resized_image = cv2.resize(img, (100, 100))
        cv2.imwrite("neg/"+str(pic_num)+".jpg",resized_image)
        pic_num += 1

    except Exception as e:
        print(str(e))  

到文件末尾,以便在VS中运行时执行该函数

这解决了您的问题,但不是很好的风格,因为无论何时导入模块,都会执行函数-通常您希望对代码的执行时间有更多的控制

要使其成为可以从命令行运行的脚本,请添加

if __name__ == '__main__':
    store_raw_images()

如果您从命令行调用脚本,这将执行函数,但是如果您将模块导入另一个模块或脚本,则函数将不会执行,直到您在运行代码时使用
store\u raw\u images()

调用该函数……我只得到了“按任意键继续…”。没有别的了。没有保存任何内容。程序应该访问带有url图像列表的页面,重新定尺寸,并将图像保存在文件夹中。成功了!!!!你不知道该怎么帮我!我是Python新手,已经尝试了几乎所有的东西!非常感谢你!很高兴知道。谢谢
if __name__ == '__main__':
    store_raw_images()