{"id":234,"date":"2012-12-18T04:44:28","date_gmt":"2012-12-17T17:44:28","guid":{"rendered":"http:\/\/www.samontab.com\/web\/?p=234"},"modified":"2021-03-03T09:37:29","modified_gmt":"2021-03-02T22:37:29","slug":"using-opencv-in-sage","status":"publish","type":"post","link":"https:\/\/www.samontab.com\/web\/2012\/12\/using-opencv-in-sage\/","title":{"rendered":"Using OpenCV in Sage"},"content":{"rendered":"<p><a href=\"http:\/\/www.opencv.org\" title=\"OpenCV official web site\" target=\"_blank\" rel=\"noopener\">OpenCV<\/a> is an awesome free open source library for computer vision, image processing, and even some machine learning.<br \/>\n<a href=\"http:\/\/www.sagemath.org\" title=\"Sage Math official web site\" target=\"_blank\" rel=\"noopener\">Sage<\/a> is an awesome free open source mathematical software system that integrates many other libraries and software into a single, easy to use interface for all your math needs.<\/p>\n<p>I really like both projects, and have been using them separately, but in this post I will show you how you can use OpenCV in the Sage environment. This means that you will be able to use all the power of the Sage Notebook Server, NumPy, SciPy, Matplotlib, PIL (Python Imaging Library), R, and almost a hundred other open source packages for all your image processing needs.<\/p>\n<p><a href=\"http:\/\/www.samontab.com\/web\/2012\/12\/using-opencv-in-sage\/sage0\/\" rel=\"attachment wp-att-238\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage0-300x292.png\" alt=\"sage0\" class=\"alignnone size-medium wp-image-238\" width=\"300\" height=\"292\" srcset=\"https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage0-300x292.png 300w, https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage0.png 598w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>The first step is to install the latest version of OpenCV in your system <strong>with the new Python bindings<\/strong>. You must have the Python bindings working correctly for this to work. The easiest way of doing this is to follow my own <a href=\"http:\/\/www.samontab.com\/web\/2012\/06\/installing-opencv-2-4-1-ubuntu-12-04-lts\/\" title=\"Installing OpenCV in Ubuntu\" target=\"_blank\" rel=\"noopener\">tutorial for installing OpenCV<\/a>. You can easily change the version for installing the latest OpenCV version that is out there, the tutorial should still work. I used it to install OpenCV 2.4.3 in Ubuntu 12.10, and it worked perfectly.<\/p>\n<p>To make sure that OpenCV is installed correctly, go to the console and start Python by running this command:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">python<\/pre>\n<p>You should see the python console waiting for you. There, write the following:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">import cv2<\/pre>\n<p><a href=\"http:\/\/www.samontab.com\/web\/2012\/12\/using-opencv-in-sage\/cv2\/\" rel=\"attachment wp-att-235\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/cv2-300x191.png\" alt=\"Importing OpenCV cv2 module into python\" class=\"alignnone size-medium wp-image-235\" width=\"300\" height=\"191\" srcset=\"https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/cv2-300x191.png 300w, https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/cv2.png 724w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><br \/>\nIf no error appeared, everything is great, you can continue. If there are some errors, you need to fix them first. You can exit with Control-D, or by typing exit().<\/p>\n<p>By the way, currently there are two OpenCV Python modules, <strong>cv<\/strong> and <strong>cv2<\/strong>. The legacy C version API of OpenCV can be accessed via cv, and the new C++ interface of OpenCV is available via cv2. Therefore, you are encouraged to use cv2 because that&#8217;s where the good stuff is.<\/p>\n<p>Now that we have OpenCV with Python correctly installed, we need to install Sage.<br \/>\nFirst, check if you are running a 32 or 64 bit system by using this command:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">uname -m<\/pre>\n<p>You will see <strong>x86_64<\/strong>, which means 64 bits or something like <strong>i686<\/strong> or <strong>i386<\/strong>, which means 32 bits.<\/p>\n<p>Now we need to download Sage from <a href=\"http:\/\/www.sagemath.org\/download-linux.html\" title=\"Sage for Linux download\" target=\"_blank\" rel=\"noopener\">here<\/a>. You can pick where to download from, as well as if you want the 32 or 64 bits version. I usually download it from the University of Washington which is where the lead developer of Sage, William Stein, teaches math but you can choose any other location that you like. You are looking for a file that has a name similar to this one: <strong>sage-5.4.1-linux-32bit-ubuntu_12.04.1_lts-i686-Linux.tar.lzma<\/strong>. For the next steps, I will be using that file. Remember that you may need to change the file or folder names for your specific situation.<\/p>\n<p>After you download the file, you will need to extract it. On the console, change your directory to where you downloaded the file and extract it:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncd ~\/Downloads\ntar --lzma -xf sage-*\n<\/pre>\n<p>Now you will have to wait for a few minutes for it to decompress a lot of files. Notice how I did not use the verbose option for extracting (I used -xf instead of -xvf). This is because it takes a lot longer to decompress when it has to output every file name. Since nothing is being printed on the screen, it is faster but you may think that nothing is happening. Don&#8217;t worry, everything is fine. Just leave it alone until it finishes decompressing.<\/p>\n<p>Now we are going to configure it so that we can call it from anywhere.<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmv sage-5.4.1-linux-32bit-ubuntu_12.04.1_lts-i686-Linux sage-5.4.1\nsudo mv sage-5.4.1 \/opt\/\nsudo cp \/opt\/sage-5.4.1\/sage \/usr\/local\/bin\/\nsudo gedit \/usr\/local\/bin\/sage\n<\/pre>\n<ol>\n<li>Copy the line that says <strong>#SAGE_ROOT=\/path\/to\/sage-version<\/strong>.<\/li>\n<li>Remove the comment character (<strong>#<\/strong>) in the line you just copied.<\/li>\n<li>Change the path to <strong>\/opt\/sage-5.4.1<\/strong> (or the version you are installing).<\/li>\n<li>Save the file and close the editor.<\/li>\n<\/ol>\n<p><a href=\"http:\/\/www.samontab.com\/web\/2012\/12\/using-opencv-in-sage\/sage_root\/\" rel=\"attachment wp-att-237\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage_root-300x229.png\" alt=\"sage_root\" class=\"alignnone size-medium wp-image-237\" width=\"300\" height=\"229\" srcset=\"https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage_root-300x229.png 300w, https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage_root.png 741w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>And now you can start Sage by using this command anywhere:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nsage\n<\/pre>\n<p>You will have to wait for a few moments this first time you run it. You should then see the command prompt of Sage waiting for your input. Exit for now by running this command:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nexit\n<\/pre>\n<p>If everything is fine, you can now delete the downloaded file to save some space:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nrm ~\/Downloads\/sage-5.4.1-linux-32bit-ubuntu_12.04.1_lts-i686-Linux.tar.lzma\n<\/pre>\n<p>OK, so now we also have Sage correctly installed in the system.<\/p>\n<p>Let&#8217;s install OpenCV into Sage:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncd \/usr\/local\/lib\/python2.7\/dist-packages\/\ncp cv2.so \/opt\/sage-5.4.1\/local\/lib\/python2.7\/site-packages\/\ncp cv.py \/opt\/sage-5.4.1\/local\/lib\/python2.7\/site-packages\/\ncd ~\n<\/pre>\n<p>To make sure that OpenCV is correctly installed in Sage, go to the console and start Sage by running this command:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">sage<\/pre>\n<p>You should see the Sage console waiting for you. There, write the following:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">import cv2<\/pre>\n<p>If no error appeared, everything is great, you can continue. If there are some errors, you need to fix them first.  At this point, it should report the following error:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nRuntimeError: module compiled against API version 6 but this version of numpy is 4.\n<\/pre>\n<p>This happens because Sage(as of v5.4.1) still comes with an older version of NumPy(v1.5.1). You can tell which is the included version of NumPy by doing this in Sage:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nimport numpy\nnumpy.version.version\nexit\n<\/pre>\n<p>So, if you have a newer version of Sage (<a href=\"http:\/\/trac.sagemath.org\/sage_trac\/ticket\/11334\" title=\"Sage with NumPy 1.7\" target=\"_blank\" rel=\"noopener\">this fix is scheduled for v5.6<\/a>), and did not get the error, you can skip the next step.<\/p>\n<p>Let&#8217;s update Sage&#8217;s NumPy to v1.7.0b2 so that we can use OpenCV with it:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncd ~\nwget https:\/\/spkg-upload.googlecode.com\/files\/numpy-1.7.0b2.spkg\nsage -f numpy-1.7.0b2.spkg\n<\/pre>\n<p>Now you should be able to run OpenCV functions in Sage.<\/p>\n<p>Let&#8217;s use the Sage Notebook interface with OpenCV.<br \/>\nStart <strong>sage<\/strong>, run <strong>notebook()<\/strong>, and follow the instructions for using the notebook interface. For more advanced options for the notebook server, you can check <a href=\"http:\/\/www.sagemath.org\/doc\/reference\/sagenb\/notebook\/notebook_object.html\" title=\"Sage notebook\" target=\"_blank\" rel=\"noopener\">here<\/a>.<\/p>\n<p>Once you have a new worksheet open, define some functions to convert arrays between NumPy, OpenCV and PIL:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nimport cv2, numpy, Image, ImageDraw\n\ndef cv2np(image):\nrgbimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nreturn rgbimage\/255.\n\ndef pil2np(image):\nrgbimage = numpy.array(image)\nreturn rgbimage\/255.\n\ndef cv2pil(image):\nrgbimage = cv2.cvtColor(lenna, cv2.COLOR_BGR2RGB)\npilimage = Image.fromarray(rgbimage)\nreturn pilimage\n<\/pre>\n<p>Now, in another cell let&#8217;s load an image and find a face using the trained frontal face model. (Make sure that you change the path to your image):<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nimage_path = \"\/home\/username\/OpenCV-2.4.3\/samples\/c\/lena.jpg\"\nlenna = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_COLOR)\ncascade_fn = \"\/usr\/local\/share\/OpenCV\/haarcascades\/haarcascade_frontalface_alt.xml\"\ncascade = cv2.CascadeClassifier(cascade_fn)\ngray = cv2.cvtColor(lenna, cv2.COLOR_BGR2GRAY)\nrects = cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=4, minSize=(30,30))\nfor x1, y1, width, height in rects:\nfaces_rectangle = &#x5B;x1, y1, x1 + width, y1 + height]\nfaces_rectangle\n<\/pre>\n<p>If you use lena.jpg, you should see the following result:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;217, 203, 386, 372]\n<\/pre>\n<p>Which is the location of the bounding box of the detected face of Lenna.<br \/>\nNow, let&#8217;s use PIL to draw the detection:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nlenna_pil = cv2pil(lenna)\ndraw = ImageDraw.Draw(lenna_pil)\ndraw.ellipse((x1, y1, x1+width, y1+height), outline=\"green\")\ndraw.ellipse((x1+1, y1+1, x1+width-1, y1+height-1), outline=\"green\")\ndraw.ellipse((x1+2, y1+2, x1+width-2, y1+height-2), outline=\"green\")\n<\/pre>\n<p>To be able of changing the thickness of the ellipse in PIL, you need to install the <a href=\"http:\/\/effbot.org\/zone\/aggdraw-index.htm\" target=\"_blank\" rel=\"noopener\">aggdraw<\/a> module, so I just drew three ellipses instead.<\/p>\n<p>Finally, it is time to show the detection:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmatrix_plot(pil2np(lenna_pil)).show( axes=True, frame=True, figsize=8, aspect_ratio=1)\n<\/pre>\n<p><a href=\"http:\/\/www.samontab.com\/web\/2012\/12\/using-opencv-in-sage\/sage_opencv\/\" rel=\"attachment wp-att-239\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage_opencv-300x182.png\" alt=\"sage_opencv\" class=\"alignnone size-medium wp-image-239\" width=\"300\" height=\"182\" srcset=\"https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage_opencv-300x182.png 300w, https:\/\/www.samontab.com\/web\/wp-content\/uploads\/2012\/12\/sage_opencv.png 923w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><br \/>\nAnd that&#8217;s it. This is just a simple example of object detection in OpenCV using the Sage environment. Feel free to explore Sage and OpenCV now that you can use them in the same interface.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>OpenCV is an awesome free open source library for computer vision, image processing, and even some machine learning. Sage is an awesome free open source mathematical software system that integrates many other libraries and software into a single, easy to use interface for all your math needs. I really like both projects, and have been [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[21,30,4],"tags":[],"class_list":["post-234","post","type-post","status-publish","format-standard","hentry","category-open-source","category-opencv","category-programming"],"_links":{"self":[{"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/posts\/234","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/comments?post=234"}],"version-history":[{"count":0,"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/posts\/234\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/media?parent=234"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/categories?post=234"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.samontab.com\/web\/wp-json\/wp\/v2\/tags?post=234"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}