利用Python和OpenCV庫將URL轉(zhuǎn)換為OpenCV格式的方法
Jun 10, 2016 pm 03:16 PM今天的博客是直接來源于我自己的個(gè)人工具函數(shù)庫。
過去幾個(gè)月,有些PyImageSearch讀者電郵問我:“如何獲取URL指向的圖片并將其轉(zhuǎn)換成OpenCV格式(不用將其寫入磁盤再讀回)”。這篇文章我將展示一下怎么實(shí)現(xiàn)這個(gè)功能。
額外的,我們也會(huì)看到如何利用scikit-image從URL下載一幅圖像。當(dāng)然前行之路也會(huì)有一個(gè)常見的錯(cuò)誤,它可能讓你跌個(gè)跟頭。
繼續(xù)往下閱讀,學(xué)習(xí)如何利用利用Python和OpenCV將URL轉(zhuǎn)換為圖像
方法1:OpenCV、NumPy、urllib
第一個(gè)方法:我們使用OpenCV、NumPy、urllib庫從URL獲取圖像,并將其轉(zhuǎn)換為圖像。打開并新建一個(gè)文件,取名url_to_image.py,我們開始吧:
# import the necessary packages import numpy as np import urllib import cv2 # METHOD #1: OpenCV, NumPy, and urllib 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) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image
首先要做的就是導(dǎo)入我們必需的包。我們將使用NumPy轉(zhuǎn)換下載的字節(jié)序?yàn)镹umPy數(shù)組,使用urllib來執(zhí)行實(shí)際的網(wǎng)絡(luò)請求,使用cv2來綁定OpenCV接口。
在第7行,我們定義了我們的url_to_image函數(shù)。這個(gè)函數(shù)帶一個(gè)url參數(shù),也就是我們想要下載的圖像地址。
接下來,在第10行,我們使用urllib庫來打開這個(gè)圖像鏈接。11行則將這個(gè)下載下來的字節(jié)序轉(zhuǎn)換為NumPy數(shù)組。
至此,NumPy數(shù)組還是一個(gè)1維數(shù)組(也就是一個(gè)長長的像素鏈表)。為了將其轉(zhuǎn)換為2維格式,假設(shè)每個(gè)像素3個(gè)通道(意即分別為紅,綠,藍(lán)通道),在12行我們使用cv.imdecode函數(shù)。最后,在15行我們返回解碼出來的圖像給調(diào)用函數(shù)。
一切就緒,該到讓它工作的時(shí)候了:
# 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", "http://www.pyimagesearch.com/wp-content/uploads/2014/12/adrian_face_detection_sidebar.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)
3-5行定義了我們將要下載和轉(zhuǎn)換為OpenCV格式的圖像地址列表。
第9行我們遍歷這個(gè)列表,13行則調(diào)用url_to_image函數(shù),然后在14行和15行將獲取的圖像顯示到屏幕上。到此呢,我們就可以像正常情況下一樣,使用OpenCV來操作和處理這些圖像了。
眼見為實(shí),打開終端,執(zhí)行如下指令:
如果一切順利的話,你會(huì)看到OpenCV的logo:
圖1:從URL下載OpenCV logo并轉(zhuǎn)換為OpenCV格式
接下來是Google的logo:
圖2:從URL下載Gooogle并轉(zhuǎn)換為OpenCV格式
這里也有在我書中驗(yàn)證人臉檢測的例子,《Practical Python and OpenCV》:
圖3:轉(zhuǎn)換一個(gè)URL圖像為OpenCV格式
現(xiàn)在,我們來看另一種獲取圖像并轉(zhuǎn)換為OpenCV格式的方法。
方法2:使用scikit-image
第二種方法假定你已經(jīng)在你計(jì)算機(jī)上安裝好了scikit-image庫。讓我們看看怎樣采用scikit-image從URL獲取圖像并將其轉(zhuǎn)換為OpenCV格式:
# METHOD #2: scikit-image from skimage import io # loop over the image URLs for url in urls: # download the image using scikit-image print "downloading %s" % (url) image = io.imread(url) cv2.imshow("Incorrect", image) cv2.imshow("Correct", cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) cv2.waitKey(0)
scikit-image庫中做得很漂亮的一點(diǎn)是:io子庫中的imread函數(shù)能夠區(qū)分圖像路徑到底在磁盤上還是一個(gè)URL(第9行)。
盡管這樣,這里有一個(gè)很嚴(yán)重的錯(cuò)誤可能讓你跌一個(gè)跟頭!
OpenCV以BGR順序表達(dá)一幅圖像,然而scikit-image則是RGB順序。如果你使用scikit-iamge的imread函數(shù),而且還想在下載完成后使用OpenCV的函數(shù),那么你要小心了。如41行所述,你需要將圖像從RBG轉(zhuǎn)換為BGR。
如果你沒有這一步,那么你可能得到錯(cuò)誤的結(jié)果:
圖4:在用scikit-image時(shí),需要特別注意將RGB轉(zhuǎn)換為BGR。左邊的圖像就是不正確的RGB順序,右邊的則是將RGB轉(zhuǎn)換為BGR,所以能正常顯示。
看看Google的logo就更明顯了
圖5:順序很重要。確保將RGB轉(zhuǎn)換為BGR,否則就留下了一個(gè)很難發(fā)現(xiàn)的bug。
到此為止,你明白了吧!這兩種方法分別使用Python、OpenCV、urllib,和scikit-image來將URL指向的圖片轉(zhuǎn)換為圖像。
總結(jié)
本文中,我們學(xué)會(huì)了如何從URL獲取圖像,且使用Python和OpenCV將其轉(zhuǎn)換為OpenCV格式。
第一種方法使用urllib包獲取圖像,使用Numpy轉(zhuǎn)換為數(shù)組,最后使用OpenCV重新構(gòu)建數(shù)組產(chǎn)生我們的圖像。
第二種方式使用scikit-image中的io.imread函數(shù)。
所以,哪種更好呢?
這完全取決于你的安裝。
如果你已經(jīng)安裝scikit-image,那么我可能就用io.imread(只是不要忘記如果要用OpenCV函數(shù)的話,要將RGB轉(zhuǎn)換為BGR)。
如果你沒有安裝scikit-image,那么url_to_image就是手邊現(xiàn)成的工具。具體細(xì)節(jié)參考本文開始處。
我很快會(huì)在Github上將這個(gè)函數(shù)添加到imutils庫中。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.
