Showing posts with label matplotlib. Show all posts
Showing posts with label matplotlib. Show all posts

Thursday, March 18, 2021

Python exercise: get RGB array of image using matplotlib

Python code to get get RGB array of image using matplotlib:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

"""
ref:
A short tutorial on plotting images with Matplotlib:
https://matplotlib.org/stable/tutorials/introductory/images.html

numpy.ndarray:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html

"""
imageFile = '/home/pi/Desktop/image.jpg'
img = mpimg.imread(imageFile)

print(type(img))
print(dir(img))

print('shape (= length of each dimension):')
print(img.shape)
print()
print(img[0][0])
print(img[0][249])
print(img[249][0])
print(img[249][249])

print()
print(img)

imgplot = plt.imshow(img)
plt.show()




Sunday, September 27, 2015

Capture Raspberry Pi Camera image, display on OpenCV, Matplotlib PyPlot and Tkinter GUI

This example capture photo from Raspberry Pi Camera Module, and display with OpenCV, Matplotlib PyPlot and Tkinter GUI.


usage:
python pyCV_picam.py 1 - display wiyh OpenCV window
python pyCV_picam.py 2 - display with matplotlib
python pyCV_picam.py 3 - display with Tkinter

import picamera
import picamera.array
import time
import cv2
from matplotlib import pyplot as plt
import Tkinter 
import Image, ImageTk
import sys

def capturePiCam():
    with picamera.PiCamera() as camera:
        cap=picamera.array.PiRGBArray(camera)
        camera.resolution = (640, 480)
        camera.start_preview()
        time.sleep(3)
        camera.capture(cap,format="bgr")
        global img
        img =cap.array

#- display on OpenCV window -
def displayAtOpenCV():
    cv2.namedWindow('imageWindow', cv2.WINDOW_AUTOSIZE)
    cv2.imshow('imageWindow',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

#- display with matplotlib -
def displayAtPyplot():
    plt.figure().canvas.set_window_title("Hello Raspberry Pi")
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()
    
#- display on Tkinter -
def displayAtThinter():
    root = Tkinter.Tk() 
    b,g,r = cv2.split(img) 
    img2 = cv2.merge((r,g,b))
    img2FromArray = Image.fromarray(img2)
    imgtk = ImageTk.PhotoImage(image=img2FromArray) 
    Tkinter.Label(root, image=imgtk).pack() 
    root.mainloop()

def displayUsage():
    print("usage: ")
    print("python pyCV_picam.py 1 - display wiyh OpenCV window")
    print("python pyCV_picam.py 2 - display with matplotlib")
    print("python pyCV_picam.py 3 - display with Tkinter")

if len(sys.argv) != 2:
    displayUsage()
    sys.exit()
    
opt = sys.argv[1]

if opt=="1":
    print("display wiyh OpenCV window")
    capturePiCam()
    displayAtOpenCV()
elif opt=="2":
    print("display with matplotlib")
    capturePiCam()
    displayAtPyplot()
elif opt=="3":
    print("display with Tkinter")
    capturePiCam()
    displayAtThinter()
else:
    displayUsage()
    



To use ImageTk in your python, refer to "Install PIL (with jpg supported) and ImageTk on Raspberry Pi/Raspbian".

Saturday, September 26, 2015

Python capture picamera image, display on OpenCV and matplotlib


Python example to capture image from Raspberry Pi Camera Module with picamera, display on OpenCV and matplotlib.

This demo run on Windows log-in Raspberry Pi 2/Raspbian remotely, so the preview will not shown.


pyCV_picam.py
import picamera
import picamera.array
import time
import cv2
from matplotlib import pyplot as plt

with picamera.PiCamera() as camera:
    cap=picamera.array.PiRGBArray(camera)
    camera.resolution = (640, 480)
    camera.start_preview()
    time.sleep(3)
    camera.capture(cap,format="bgr")
    img=cap.array
    
#- display on OpenCV window -
cv2.namedWindow('imageWindow', cv2.WINDOW_AUTOSIZE)
cv2.imshow('imageWindow',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

#- display with matplotlib
#plt.figure().canvas.set_window_title("Hello Raspberry Pi")
#plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
#plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
#plt.show()




more:
~ Display on Tkinter GUI also.

Raspberry Pi + Python/OpenCV, draw something on OpenCV image


Example to draw something on OpenCV image.


pyCV_draw.py
import platform
import os
import sys
import cv2
import numpy
import urllib
import matplotlib
from matplotlib import pyplot as plt

print platform.system(), platform.release(), platform.dist()
print os.uname()
print("Python version: \n" + sys.version)
print("cv2 version: " + cv2.__version__)
print("numpy version: " + numpy.__version__)
print("urllib version: " + urllib.__version__)
print("matplotlib version: " + matplotlib.__version__)

#- load image from local file
#img = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)

#- load image from internet
url = 'http://goo.gl/41cgQr'
data = urllib.urlopen(url)
img = numpy.asarray(bytearray(data.read()), dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_COLOR)

#draw something
#ref: 
#http://docs.opencv.org/master/dc/da5/tutorial_py_drawing_functions.html
cv2.line(img,(0,0),(511,511),(255,0,0),5)
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv2.circle(img,(447,63), 63, (0,0,255), -1)
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
pts = numpy.array([[10,5],[20,30],[70,20],[50,10]], numpy.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(0,255,255))
font = cv2.FONT_HERSHEY_SIMPLEX
# AttributeError: 'module' object has no attribute 'LINE_AA'
# to solve it, change 'LINE_AA' to 'CV_AA'
#cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.CV_AA)

#- display on OpenCV window -
#cv2.namedWindow('imageWindow', cv2.WINDOW_AUTOSIZE)
#cv2.imshow('imageWindow', img)
#cv2.waitKey(0)
#cv2.destroyWindow('imageWindow')

#sys.exit()

#- display with matplotlib
#set window title of matplotlib plt
plt.figure().canvas.set_window_title("Hello Raspberry Pi") 
#-- incorrect color
#plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
#-- correct color with cv2.cvtColor()
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.title("Hello Raspberry Pi")
plt.suptitle("http://helloraspberrypi.blogspot.com/")

plt.show()


Wednesday, September 23, 2015

Raspberry Pi + Python/OpenCV, display image on matplotlib pyplot


With OpenCV image displayed using matplotlib pyplot, we can resize the window, also save the image on storage. This Python example run on Raspberry Pi 2, show how to load JPG image from internet, display on pyplot, save to local storage in PNG format, then open and display the saved local image.


import platform
import os
import sys
import cv2
import numpy
import urllib
import matplotlib
from matplotlib import pyplot as plt

print platform.system(), platform.release(), platform.dist()
print os.uname()
print("Python version: \n" + sys.version)
print("cv2 version: " + cv2.__version__)
print("numpy version: " + numpy.__version__)
print("urllib version: " + urllib.__version__)
print("matplotlib version: " + matplotlib.__version__)

#- load image from local file
#img = cv2.imread('test.png', cv2.IMREAD_UNCHANGED)

#- load image from internet
url = 'http://goo.gl/41cgQr'
data = urllib.urlopen(url)
img = numpy.asarray(bytearray(data.read()), dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_COLOR)

#- display on OpenCV window -
#cv2.namedWindow('imageWindow', cv2.WINDOW_AUTOSIZE)
#cv2.imshow('imageWindow', img)
#cv2.waitKey(0)
#cv2.destroyWindow('imageWindow')

#- display with matplotlib
#set window title of matplotlib plt
plt.figure().canvas.set_window_title("Hello Raspberry Pi") 
#-- incorrect color
#plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
#-- correct color with cv2.cvtColor()
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.title("Hello Raspberry Pi")
plt.suptitle("http://helloraspberrypi.blogspot.com/")

plt.show()

~ To use matplotlib with Python 2 on Raspberry Pi, refer "Install numpy, matplotlib and drawnow for Python 2".

Wednesday, April 8, 2015

Plot RPi 2 core temperature using Python 2 and matplotlib.pyplot

Similar to the previous example "Display Raspberry Pi CPU temperature graphically, using Python 2 with Matplotlib and drawnow", but use library of matplotlib.pyplot only, no drawnow.


import os
import matplotlib.pyplot as plt

tempC = []
plt.ion()
cnt=0

def plotNow():
    plt.clf()
    plt.ylim(20,80)
    plt.title('Raspberry Pi core temperture')
    plt.grid(True)
    plt.ylabel('Temp C')
    plt.plot(tempC, 'rx-', label='Degrees C')
    plt.legend(loc='upper right')
    plt.plot(tempC)
    plt.show()

#pre-load dummy data
for i in range(0,26):
    tempC.append(0)
    
while True:
    ostemp = os.popen('vcgencmd measure_temp').readline()
    temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
    print(temp)
    tempC.append(temp)
    tempC.pop(0)
    plotNow()
    plt.pause(.5)



Monday, March 30, 2015

Python display CPUs frequency graphically, run on Raspberry Pi 2/Linux


In Linux, the file "/sys/devices/system/cpu/*/cpufreq/scaling_cur_freq" show the available frequency your CPU(s) are scaled to currently, in KHz.

In Raspberry Pi 2/Raspbian, where is:
/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
/sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq
/sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq
/sys/devices/system/cpu/cpu3/cpufreq/scaling_cur_freq

This Python 2 example run on Raspberry Pi 2, to display CPU frequency graphically. (It seem that all CPU run on the same frequency)


plotCpuFreq.py
import os
import matplotlib.pyplot as plt
from drawnow import *

# Run on Raspberry Pi 2
# 4 CPUs
cpu0Freq = []
cpu1Freq = []
cpu2Freq = []
cpu3Freq = []

plt.ion()
cnt=0

def plotCpuFreq():
    plt.ylim(0,1500000)
    plt.title('Raspberry Pi 2 CPUs Frequency')
    plt.grid(True)
    plt.ylabel('KHz')
    plt.plot(cpu0Freq, 'r^-', label='cpu0')
    plt.plot(cpu1Freq, 'c>-', label='cpu1')
    plt.plot(cpu2Freq, 'bv-', label='cpu2')
    plt.plot(cpu3Freq, 'm<-', label='cpu3')
    plt.legend(loc='upper right')

#pre-load dummy data
for i in range(0,100):
    cpu0Freq.append(0)
    cpu1Freq.append(0)
    cpu2Freq.append(0)
    cpu3Freq.append(0)
    
while True:
    cpu0 = os.popen("awk '{print $1}' /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq").readline()
    cpu1 = os.popen("awk '{print $1}' /sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq").readline()
    cpu2 = os.popen("awk '{print $1}' /sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq").readline()
    cpu3 = os.popen("awk '{print $1}' /sys/devices/system/cpu/cpu3/cpufreq/scaling_cur_freq").readline()

    print(cpu0 + " " + cpu1 + " " + cpu2 + " " + cpu3)
    cpu0Freq.append(cpu0)
    cpu0Freq.pop(0)
    cpu1Freq.append(cpu1)
    cpu1Freq.pop(0)
    cpu2Freq.append(cpu2)
    cpu2Freq.pop(0)
    cpu3Freq.append(cpu3)
    cpu3Freq.pop(0)
    
    drawnow(plotCpuFreq)
    plt.pause(1)



To install needed libraries on Raspberry Pi, refer to "Install numpy, matplotlib and drawnow for Python 2".


The almost same code run on Linux with dual core.


plot2CpuFreq.py
import os
import matplotlib.pyplot as plt
from drawnow import *

# Run on Dual Core Atom
# with 2 CPU
cpu0Freq = []
cpu1Freq = []

plt.ion()
cnt=0

def plotCpuFreq():
    plt.ylim(0,2000000)
    plt.title('Dual Core CPUs Frequency')
    plt.grid(True)
    plt.ylabel('KHz')
    plt.plot(cpu0Freq, 'r^-', label='cpu0')
    plt.plot(cpu1Freq, 'c>-', label='cpu1')
    plt.legend(loc='upper right')

#pre-load dummy data
for i in range(0,100):
    cpu0Freq.append(0)
    cpu1Freq.append(0)
    
while True:
    cpu0 = os.popen("awk '{print $1}' /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq").readline()
    cpu1 = os.popen("awk '{print $1}' /sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq").readline()

    print(cpu0 + " " + cpu1)
    cpu0Freq.append(cpu0)
    cpu0Freq.pop(0)
    cpu1Freq.append(cpu1)
    cpu1Freq.pop(0)
    
    drawnow(plotCpuFreq)
    plt.pause(1)



Sunday, March 29, 2015

Python display Raspberry Pi load average graphically

The file /proc/loadavg indicate the load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O (state D) averaged over 1, 5, and 15 minutes. This Python 2 example read the first figure (over 1 minutes) every second, and plot to figure using Matplotlib.


plotLoadAvg.py
import os
import matplotlib.pyplot as plt
from drawnow import *

loadavg = []

plt.ion()
cnt=0

def plotLoadAvg():
    plt.ylim(0,4)
    plt.title('Raspberry Pi load average')
    plt.grid(True)
    plt.ylabel('usage')
    plt.plot(loadavg, 'bo-', label='usage')
    plt.legend(loc='upper right')

#pre-load dummy data
for i in range(0,100):
    loadavg.append(0)
    
while True:

    usage = os.popen("awk '{print $1}' /proc/loadavg").readline()
    print(usage)
    loadavg.append(usage)
    loadavg.pop(0)
    drawnow(plotLoadAvg)
    plt.pause(1)



For installation of the libraries, read "Install numpy, matplotlib and drawnow for Python 2".

Display Raspberry Pi CPU temperature graphically, using Python 2 with Matplotlib and drawnow

Python 2 example to display Raspberry Pi CPU temperature graphically, with Matplotlib and drawnow.



This exercise work on Python 2 and need matplotlib and drawnow, refer to "Install numpy, matplotlib and drawnow for Python 2".

plotTemp.py
import os
import matplotlib.pyplot as plt
from drawnow import *

tempC = []

plt.ion()
cnt=0

def plotTempC():
    plt.ylim(20,80)
    plt.title('Raspberry Pi core temperture')
    plt.grid(True)
    plt.ylabel('Temp C')
    plt.plot(tempC, 'rx-', label='Degrees C')
    plt.legend(loc='upper right')

#pre-load dummy data
for i in range(0,26):
    tempC.append(0)
    
while True:

    ostemp = os.popen('vcgencmd measure_temp').readline()
    temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
    print(temp)
    tempC.append(temp)
    tempC.pop(0)
    drawnow(plotTempC)
    plt.pause(.5)





For Python 3:

Matplotlib for Python 3 is not support currently. I tried to build it from source (refer "Install numpy, matplotlib and drawnow for Python 2" and "Fail to build matplotlib for Python3, run on Raspberry Pi 2"), but nothing plotted while running.



Similar example without using drawnow, "Plot RPi 2 core temperature using Python 2 and matplotlib.pyplot".

Fail to build matplotlib for Python3, run on Raspberry Pi 2

matplotlib is not support Python 3 on Raspberry Pi/Raspbian currently. I tried to build from source. Even success in build (with something error in middle steps), install, and import in IDLE 3. But fail (nothing plotted) in running.

Here is my steps to build matplotlib on Raspberry Pi 2/Raspbian:
$ sudo apt-get install python3-dev
$ git clone https://github.com/matplotlib/matplotlib
$ cd matplotlib
$ python3 setup.py build
$ sudo python3 setup.py install


BUT, fail to plot anything at run time! refer to the post "Display Raspberry Pi CPU temperature graphically, using Python 2 with Matplotlib".


Install numpy, matplotlib and drawnow for Python 2

This post show steps to install numpy, matplotlib and drawnow for Python 2 on Raspberry Pi, to prepare my exercise "Display Raspberry Pi CPU temperature graphically, using Python 2 with Matplotlib". The steps are same as in other Linux such as Ubuntu.

To check if your system have numpy, matplotlib and drawnow installed, enter the command in Python Shell:

>>> import numpy
>>> import matplotlib
>>> import drawnow

If you get error message like this, you have to install it.
ImportError: No module named numpy
ImportError: No module named matplotlob
ImportError: No module named drawnow

Install numpy, matplotlib and drawnow for Python 2:
$ sudo apt-get install python-numpy
$ sudo apt-get install python-matplotlib
$ sudo apt-get install python-pip
$ sudo pip install drawnow




For Python 3:

To install numpy and drawnow for Python 3 on Raspberry Pi, enter the command:
Install for Python 3:
$ sudo apt-get install python3-numpy
$ sudo apt-get install python3-pip
$ sudo pip-3.2 install drawnow

For matplotlib for Python 3, it seem not supported on Raspbian currently. I tried to build from source, refer to the post "Fail to build matplotlib for Python3, run on Raspberry Pi 2".