使用jupyter(IPython)開發opencv

opencv 的默認使用highgui顯示圖片,
用命令行運行,能夠正常顯示html

cv.namedWindow("Image")
cv.imshow("Image",img)複製代碼

用jupyter則有無反應python

本文環境

import sys
import cv2
print("python版本:%s"% sys.version)
print("opencv版本:%s"% cv2.__version__)複製代碼

輸出web

python版本:3.5.3 |Continuum Analytics, Inc.| (default, May 15 2017, 10:43:23) [MSC v.1900 64 bit (AMD64)]
opencv版本:3.2.0複製代碼

安裝opencv

若是使用Anaconda,則打開 Anaconda Prompt,activate python35切換到相應的python環境bash

pip install --upgrade setuptools
pip install numpy Matplotlib
pip install opencv-python複製代碼

參考 Python環境搭建之OpenCV,可是在jupyter中,運行該博文下一段demo代碼,無反應網絡

通過一番google,已解決,現整理以下post

jupyter顯示opencv圖片

lenna 圖爲例ui

import cv2
from matplotlib import pyplot as plt

img = cv2.imread('lenna1.png')

show_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 

plt.imshow(show_img)
plt.show()複製代碼

參考自 Quickie: Mix up OpenCV and Jupyter (iPython Notebook) 和官方 Using Matplotlibgoogle

opencv讀取網絡圖片

%matplotlib inline
import numpy as np
import cv2
from matplotlib import pyplot as plt
import urllib.request as ul

data = None

try:

    data = ul.urlopen('http://www.mupin.it/wp-content/uploads/2012/06/lenna1.png').read()

except Exception as e:

    print("Could not download the image: %s " %( e.message))

else:
    data =  np.fromstring(data, np.uint8)
    img_data =  cv2.imdecode(data, cv2.IMREAD_COLOR )
    img_data = cv2.cvtColor(img_data, cv2.COLOR_BGR2RGB)
    plt.imshow(img_data)
    plt.show()複製代碼

本示例用的環境是python:3.5.3 和 opencv:3.2.0,在opencv3.x中已經不存在cv2.CV_LOAD_IMAGE_COLOR,根據 Python OpenCV load image from byte string ,改爲cv2.IMREAD_COLORurl

大部分代碼 參考自 Quickie: Grab an image from the web with urllib2 and OpenCVspa

OpenCV入門教程

博客 anjia.ml/2017/07/16/…
掘金 juejin.im/post/596b3e…
簡書 www.jianshu.com/p/69af8b1dc…

相關文章
相關標籤/搜索