在OpenCV中通过图片的URL地址获取图片:

# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2

# URL到图片
def url_to_image(url):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urllib.urlopen(url)
    # bytearray将数据转换成(返回)一个新的字节数组
    # asarray 复制数据,将结构化数据转换成ndarray
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    # cv2.imdecode()函数将数据解码成Opencv图像格式
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    # return the image
    return image

# initialize the list of image URLs to download
urls = [
    "http://www.pyimagesearch.com/wp-content/uploads/2015/01/opencv_logo.png",
    "http://www.pyimagesearch.com/wp-content/uploads/2015/01/google_logo.png"
]

# loop over the image URLs
for url in urls:
    # download the image URL and display it
    print "downloading %s" % (url)
    image = url_to_image(url)
    cv2.imshow("Image", image)
    cv2.waitKey(0)

以上过程用到bytearray、numpy.asarray、cv2.imdecode



Python bytearray()


bytearray是Python内的一个类,bytearray()返回一个新字节数组,可以看做是array的字节表示。bytearray()需要一个数组作为参数,这个数组里的元素是可变的,并且数组里每个元素的值范围是: 0 <= x < 256。

bytearray()使用:

# -*- coding: utf-8 -*-
a = bytearray()
b = bytearray([1,2,3,4,5])
c = bytearray('ABC','UTF-8')
d = bytearray(u'中文','UTF-8')
print type(a)
print type(b)
print c
print d
print(len(a))
print(len(b))
print(len(c))
print(len(d))

输出:

<type 'bytearray'>
<type 'bytearray'>
ABC
中文
0
5
3
6


numpy.asarray()


numpy.asarray()函数的作用是将输入数据(列表的列表,元组的元组,元组的列表等结构化数据)转换为numpy中矩阵(ndarray、多维数组对象)的形式。

# -*- coding: utf-8 -*-
import numpy as np

data1=[[1,2,3],[1,2,3],[1,2,3]]
data2=[(1,2,3),(1,2,3),(1,2,3)]
data3=[(1,2,3,1,2,3,1,2,3)]
data4=[1,2,3,1,2,3,1,2,3]

arr1=np.array(data1)
arr2=np.array(data1)
arr3=np.array(data3)
arr4=np.array(data4)

print arr1
print arr2
print arr3
print arr4

输出:

[[1 2 3]
 [1 2 3]
 [1 2 3]]
[[1 2 3]
 [1 2 3]
 [1 2 3]]
[[1 2 3 1 2 3 1 2 3]]
[1 2 3 1 2 3 1 2 3]


指定转换类型

# -*- coding: utf-8 -*-
import numpy as np

data1=[[1,2,3],[1,2,3],[1,2,3]]
data2=[(1,2,3),(1,2,3),(1,2,3)]
data3=[(1,2,3,1,2,3,1,2,3)]
data4=[1,2,3,1,2,3,1,2,3]

arr1=np.array(data1,'f')
arr2=np.array(data1,'f')
arr3=np.array(data3,'f')
arr4=np.array(data4,'f')

print arr1
print arr2
print arr3
print arr4

'f'表示float浮点型,输出:

[[ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]]
[[ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]]
[[ 1.  2.  3.  1.  2.  3.  1.  2.  3.]]
[ 1.  2.  3.  1.  2.  3.  1.  2.  3.]

array和asarray都可以将结构数据转化为ndarray,但是主要区别就是当数据源是ndarray时,array仍然会copy出一个副本,占用新的内存,但asarray不会,跟数据源指向同一块内存。

posted on 2018-01-25 20:37  未雨愁眸  阅读(726)  评论(0编辑  收藏  举报