“HDF” stands for “Hierarchical Data Format”. Every object in an HDF5 file has a name, and they’re arranged in a POSIX-style hierarchy with/-separators:
最基本的操作,讀,寫,更新
Read HDF5
import h5py
filename ='file.hdf5'
f = h5py.File(filename,'r')# List all groupsprint("Keys: %s"% f.keys())
a_group_key = list(f.keys())[0]# Get the data
data = list(f[a_group_key])
Write HDF5
#!/usr/bin/env pythonimport h5py
# Create random dataimport numpy as np
data_matrix = np.random.uniform(-1,1, size=(10,3))# Write data to HDF5
data_file = h5py.File('file.hdf5','w')
data_file.create_dataset('group_name', data=data_matrix)
data_file.close()
另一個讀取範例
Reading the file
import h5py
f = h5py.File(file_name, mode)
Studying the structure of the file by printing what HDF5 groups are present
for key in f.keys():print(key)#Names of the groups in HDF5 file.
Extracting the data
#Get the HDF5 group
group = f[key]#Checkout what keys are inside that group.for key in group.keys():print(key)
data = group[some_key_inside_the_group].value
#Do whatever you want with data#After you are done
f.close()
gcc main.c /usr/local/foo/lib/liboperator.so -o main
也可以像這樣:
gcc main.c -L /usr/local/foo/lib -loperator -o main
共享函式在程式啟動時期會檢查是否存在。以一個分別鏈結了靜態函式與共享函式的binary而言,執行的結果大有差別。以靜態函式鏈結的main程式可以順利執行,但是假設系統預設尋找函式庫的路徑裡找不到liboperator.so,以共享函式鏈結的main程式則會出現錯誤訊息: ./main: error while loading shared libraries: liboperator.so: cannot open shared object file: No such file or directory
這時解決的方法有四種:
import time
import sys
import RPi.GPIO as GPIO
def step_8 (p):
if p==0:
GPIO.output(5,0)
GPIO.output(6,0)
GPIO.output(12,0)
GPIO.output(13,0)
if p==1:
GPIO.output(5,1)
GPIO.output(6,0)
GPIO.output(12,0)
GPIO.output(13,0)
if p==2:
GPIO.output(5,1)
GPIO.output(6,1)
GPIO.output(12,0)
GPIO.output(13,0)
if p==3:
GPIO.output(5,0)
GPIO.output(6,1)
GPIO.output(12,0)
GPIO.output(13,0)
if p==4:
GPIO.output(5,0)
GPIO.output(6,1)
GPIO.output(12,1)
GPIO.output(13,0)
if p==5:
GPIO.output(5,0)
GPIO.output(6,0)
GPIO.output(12,1)
GPIO.output(13,0)
if p==6:
GPIO.output(5,0)
GPIO.output(6,0)
GPIO.output(12,1)
GPIO.output(13,1)
if p==7:
GPIO.output(5,0)
GPIO.output(6,0)
GPIO.output(12,0)
GPIO.output(13,1)
if p==8:
GPIO.output(5,1)
GPIO.output(6,0)
GPIO.output(12,0)
GPIO.output(13,1)
def step_4 (p):
if p==0:
GPIO.output(5,0)
GPIO.output(6,0)
GPIO.output(12,0)
GPIO.output(13,0)
if p==1:
GPIO.output(5,1)
GPIO.output(6,1)
GPIO.output(12,0)
GPIO.output(13,0)
if p==2:
GPIO.output(5,0)
GPIO.output(6,1)
GPIO.output(12,1)
GPIO.output(13,0)
if p==3:
GPIO.output(5,0)
GPIO.output(6,0)
GPIO.output(12,1)
GPIO.output(13,1)
if p==4:
GPIO.output(5,1)
GPIO.output(6,0)
GPIO.output(12,0)
GPIO.output(13,1)
用另一種寫法
def steps_8(value):
print value
global pas
if(value<0):
for i in range (0,abs(value)):
step_8(pas)
time.sleep(0.005)
pas+=1
if(pas>=9):
pas=1;
else:
for i in range (0,abs(value)):
step_8(pas)
time.sleep(0.005)
if(pas==1):
pas=9;
pas-=1
step_8(0)
def steps_4(value):
print value
global pas
if(value<0):
for i in range (0,abs(value)):
step_4(pas)
time.sleep(0.005)
pas+=1
if(pas>=5):
pas=1;
else:
for i in range (0,abs(value)):
step_4(pas)
time.sleep(0.005)
if(pas==1):
pas=5;
pas-=1
step_4(0)
主程式
if __name__ == "__main__":
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(6, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
step_4(0)
pas=1
print len(sys.argv)
if(len(sys.argv)<2):
print ("Parameter error")
print ("Usage: sudo python steeper.py val mode")
print ("val = step number >0clockwise, <0 anticlockwise ")
print ("mode = 0: 8 phase 2: 1 phase ")
else:
st=int(sys.argv[1])
if(len(sys.argv)==3 and sys.argv[2]=="1"):
print("8 phase moving")
steps_8(st)
else:
print("4 phase moving")
steps_4(st)
測試:
python stepper.py -500 0
# 500 steps anti clockwise full step mode
python stepper.py 800 1
# 800 steps clockwise, half-step mode.
#----------------------------------
Example2:
Python: stepper.py
#!/usr/bin/python
# Import required libraries
importsys
importtime
importRPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO signals to use
# Physical pins 11,15,16,18
# GPIO17,GPIO22,GPIO23,GPIO24
StepPins =[17,22,23,24]
# Set all pins as output
forpin inStepPins:
print"Setup pins"
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin, False)
# Define advanced sequence
# as shown in manufacturers datasheet
Seq =[[1,0,0,1],
[1,0,0,0],
[1,1,0,0],
[0,1,0,0],
[0,1,1,0],
[0,0,1,0],
[0,0,1,1],
[0,0,0,1]]
StepCount =len(Seq)
StepDir =1# Set to 1 or 2 for clockwise
# Set to -1 or -2 for anti-clockwise
# Read wait time from command line
iflen(sys.argv)>1:
WaitTime =int(sys.argv[1])/float(1000)
else:
WaitTime =10/float(1000)
# Initialise variables
StepCounter =0
# Start main loop
whileTrue:
printStepCounter,
printSeq[StepCounter]
forpin inrange(0,4):
xpin=StepPins[pin]# Get GPIO
ifSeq[StepCounter][pin]!=0:
print" Enable GPIO %i"%(xpin)
GPIO.output(xpin, True)
else:
GPIO.output(xpin, False)
StepCounter +=StepDir
# If we reach the end of the sequence
# start again
if(StepCounter>=StepCount):
StepCounter =0
if(StepCounter<0):
StepCounter =StepCount+StepDir
# Wait before moving on
time.sleep(WaitTime)
python stepper.py 20
測試 20 milliseconds
#--------------------------------------
Example3 : A Python class to move the stepper motor
where-clock/Stepper.py (Source)
#!/usr/bin/env python
# the 28BJY-48 stepper motor with ULN2003 control board.
from time import sleep
import RPi.GPIO as GPIO
class Motor(object):
def __init__(self, pins, mode=3):
"""Initialise the motor object.
pins -- a list of 4 integers referring to the GPIO pins that the IN1, IN2
IN3 and IN4 pins of the ULN2003 board are wired to
mode -- the stepping mode to use:
1: wave drive (not yet implemented)
2: full step drive
3: half step drive (default)
"""
self.P1 = pins[0]
self.P2 = pins[1]
self.P3 = pins[2]
self.P4 = pins[3]
self.mode = mode
self.deg_per_step = 5.625 / 64 # for half-step drive (mode 3)
self.steps_per_rev = int(360 / self.deg_per_step) # 4096
self.step_angle = 0 # Assume the way it is pointing is zero degrees
for p in pins:
GPIO.setup(p, GPIO.OUT)
GPIO.output(p, 0)
def _set_rpm(self, rpm):
"""Set the turn speed in RPM."""
self._rpm = rpm
# T is the amount of time to stop between signals
self._T = (60.0 / rpm) / self.steps_per_rev
# This means you can set "rpm" as if it is an attribute and
# behind the scenes it sets the _T attribute
rpm = property(lambda self: self._rpm, _set_rpm)
def move_to(self, angle):
"""Take the shortest route to a particular angle (degrees)."""
# Make sure there is a 1:1 mapping between angle and stepper angle
target_step_angle = 8 * (int(angle / self.deg_per_step) / 8)
steps = target_step_angle - self.step_angle
steps = (steps % self.steps_per_rev)
if steps > self.steps_per_rev / 2:
steps -= self.steps_per_rev
print "moving " + `steps` + " steps"
if self.mode == 2:
self._move_acw_2(-steps / 8)
else:
self._move_acw_3(-steps / 8)
else:
print "moving " + `steps` + " steps"
if self.mode == 2:
self._move_cw_2(steps / 8)
else:
self._move_cw_3(steps / 8)
self.step_angle = target_step_angle
if __name__ == "__main__":
GPIO.setmode(GPIO.BOARD)
m = Motor([18,22,24,26])
m.rpm = 5
print "Pause in seconds: " + `m._T`
m.move_to(90)
sleep(1)
m.move_to(0)
sleep(1)
m.mode = 2
m.move_to(90)
sleep(1)
m.move_to(0)
GPIO.cleanup()
the motor round by 90 degrees, pause for 1 second, move it back again
#--------------------------------
28BYJ-48 Stepper Motor with ULN2003 driver and Arduino Uno
5 volts DC => about 15+ RPM 12 volts DC => about 25+ RPM.
28BYJ-48 Stepper Motor 特性
Motor Type
Unipolar stepper motor
Connection Type
5 Wire Connection (to the motor controller)
Voltage
5-12 Volts DC
Frequency
100 Hz
Step mode
Half-step mode recommended (8 step control signal sequence)
Step angle
Half-step mode: 8 step control signal sequence (recommended)5.625 degrees per step / 64 steps per one revolution of the internal motor shaftFull Step mode: 4 step control signal sequence11.25 degrees per step / 32 steps per one revolution of the internal motor shaft
Gear ratio
Manufacturer specifies64:1. Some patient and diligent people on theArduino forumshave disassembled the gear train of these little motors and determined that the exact gear ratio is in fact63.68395:1. My observations confirm their findings. These means that in the recommended half-step mode we will have:64 steps per motor rotation x 63.684 gear ratio = 4076 steps per full revolution (approximately).
Wiring to the ULN2003 controller
A (Blue), B (Pink), C (Yellow), D (Orange), E (Red, Mid-Point)
Weight
30g
Model : 28BYJ-48
Rated voltage : 5VDC
Number of Phase : 4
Speed Variation Ratio : 1/64
Stride Angle : 5.625° /64
Frequency : 100Hz
DC resistance : 50Ω±7%(25℃)
Idle In-traction Frequency : > 600Hz
Idle Out-traction Frequency : > 1000Hz
In-traction Torque >34.3mN.m(120Hz)
Self-positioning Torque >34.3mN.m
Friction torque : 600-1200 gf.cm
Pull in torque : 300 gf.cm
Insulated resistance >10MΩ(500V)
Insulated electricity power :600VAC/1mA/1s
Insulation grade :A
Rise in Temperature <40K(120Hz)
Noise <35dB(120Hz,No load,10cm)
#!/usr/bin/python
prg_n = 'ServerSocketDemo-from-v29'
#
# This needs to be running on 'Server' BEFORE starting ESP8266 routine
#
import time; import socket; import os; import glob
port = 1247
i_cnt=0
#
# **** While True Loop ****
while True:
s = socket.socket()
host = socket.gethostname()
print host, port
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # added allow to reuse when re-run
s.bind(('',port)) # Needed (('',port)) or client never saw it
s.listen(5)
c, addr = s.accept()
# end of setting socket
#
print 'c, addr: ', c, addr
print 'Waiting for data from ESP8266...'
# it printed... c, addr: <socket._socketobject object at 0x7ff4d063c670> ('192.168.1.200', 3073)
print("Connection accepted from " + repr(addr[1]) + " Server ready for file transfer...\n")
# it printed... Connection accepted from xxxx Server ready for file transfer...
#
# ACK the client, get filename and open file for writes
starttime = time.time() # measure start of ET to get and write file
c.send("ACK...\n") # SEND MESSAGE TO CLIENT TO SEND DATA
#
tfile = "Server-WIP"
fobj = open(tfile, "w")
#
# Incoming Data, loop until "FILE-EOF", then repeat for additional file(s)
# get next line...
client_sent = c.recv(1026)
#
while client_sent != 'EOF\n' :
print client_sent, # comma supresses a linefeed from printer (string already has a linefeed)
fobj.write(client_sent)
client_sent = c.recv(1026)
#
######### HIT EOF\n
localtime = time.asctime( time.localtime(time.time()) )
print (localtime)
E_Time = (time.time() - starttime)
print "Elapsed Time: %.2f Seconds" % E_Time
fobj.write("Server:,,,,,Elapsed Time: %.2f Seconds" % E_Time + '\n' )
fobj.write("Server:,,,,,Program Name: %s " %prg_n + '\n' )
fobj.close()
os.chmod(tfile,0o666) # assign RW- to Owner, Group, Other
os.rename(tfile, tfile[0:18] + '-' + str(i_cnt))
i_cnt += 1
print ('addr[1]: '+repr(addr[1])+' FILE XFER DONE for: '+tfile[0:18]+'-'+ str(i_cnt))
#
### close the socket
### a new socket will be created for next upload;
### as the client closes its socket after uploads
###
print ('ALL FILES RCVD this session')
print ('close socket, open new socket and wait for next upload')
print ('Back to top level # "**** While True Loop ****"\nServer Prog: ' + prg_n)
s.close()
ESP8266 as Client (Station mode)
prg_n='ESP_SocketDemo.py'
#
# NOTE - Server socket must be up and running first
# This prog uploads the first file found in '/DATA' dir on the ESP8266
# Must first create '/DATA' and save a text file there
#
print(prg_n)
host='192.168.1.100';port=1247
my_ssid='ENTER-YOUR_SSID_HERE'
my_wifi_pw='ENTER_YOUR_NETWORK_PASSWORD_HERE'
#
import sys,time,utime,socket,network,machine
from ntptime import settime
from machine import Pin
#
uos.chdir('/DATA')# must be pre set up on ESP8266, add a text file demo here
#
# main code loop below, afer defs...
#
def set_WIFI(cntrl):
i=0;sta_if=network.WLAN(network.STA_IF)
if cntrl=='ON':
if not sta_if.isconnected():
print('conn WiFi')
sta_if.active(True)
sta_if.connect(my_ssid,my_wifi_pw)
while not sta_if.isconnected():
print(".",end="")
time.sleep(1);i+=1
if i>9:return#>>
else:sta_if.active(False)
print('NW CFG:',sta_if.ifconfig())
#
#
def upld_data():
sd=.3 # delay between sends - experiment with this
df='' # data file name
p16.high();red_LED=False
fl=uos.listdir()
df=fl[0]
print('fl: ',fl,' dl: ',dl)
#
set_WIFI('ON')
s=socket.socket();time.sleep(sd)
try:
s.connect((host,port))
except Exception as err:
print('SockConn-ERR#: ',err)
return('NOP')#>>
#
cmd=s.recv(1024)
if cmd.startswith('ACK'): # I have Server send 'ACK' on connect
print('SRV-ACK')
else:#catch???
print(cmd+' SRV-NO-ACK')
s.close();return('NOP')#>>
#
print(df)
s.send(df);time.sleep(sd)
with open(df,'r') as fobj:
for line in fobj: # will loop here until end-of-file
print(line,end='')
if red_LED == False:#toggle LED during sends
p16.low();red_LED=True
else:
p16.high();red_LED=False
s.send(line);time.sleep(sd)
p16.low();red_LED=True
#
# following is extra info I send after the file has been read
s.send('\nprg_n: '+prg_n+', Free MEM:,'+str(gc.mem_free())+'\n')
time.sleep(sd)
s.send('fl is: '+str(fl)+'\n')
time.sleep(sd)
fl=uos.statvfs('/')
fl='Tot/Used/Free %d blocks: %d/%d/%d\n' %(fl[0],fl[2],fl[2]-fl[3],fl[3])
print(fl)
s.send(fl);time.sleep(sd)
s.send('EOF\n') # Server will look for EOF message from ESP, finish,
# close/open its socket, loop back, wait for next upload
p16.high()
return('DONE')#>>
#
#END DEF
#
while True: # upload every 60 seconds
if utime.time() % 60 == 0:
df_status = upld_data()
print (df_status)
time.sleep(1)
gc.collect()
#
#
使用Raspberry Pi 的GPIO library 去產生PWM,進而控制DC 直流馬達的工作電壓及速度,是我們經常拿來討論的方法及議題,使用方法很簡單
我們只要使用二個指令即可以設定工作頻率及工作週期,利用這二個指令就可以改變及控制PWM GPIO的工作電壓進而達到控制直流馬達速度的目地。
至於想了解PWM及工作原理及說明設定可以利用Google或參考下面的網站software PWM – How to use it說明,這不是本篇文章要說明的重點。
本篇要思考的重點是要如何設定PWM的工作頻率,很多文章都提到首先先利用這個指令設定頻率GPIO.PWM(GPIO接脚,頻率設定),但問題是我們要設定多少的工作頻率才可以,什麼是最小值和最大值,這個值的大小是否會改變PWM的輸出電壓。
p = GPIO.PWM(25, 50) # create an object p for PWM on port 25 at 50 Hertz
# you can have more than one of these, but they need
# different names for each port
# e.g. p1, p2, motor, servo1 etc.
p.start(50) # start the PWM on 50 percent duty cycle
# duty cycle value can be 0.0 to 100.0%, floats are OK
p.ChangeDutyCycle(90) # change the duty cycle to 90%
p.ChangeFrequency(100) # change the frequency to 100 Hz (floats also work)
問題一: PWM頻率的最大值
這個問題終於了答案,而且還真是令人想不到的測試結果。這個問題關連到你的硬體設備工作頻率及使用的語言及library。
當使用Raspberry Pi 時GPIO接脚的反應速度可以多快, 這篇文章是利用Raspberry Pi 來產生方波頻率Benchmarking Raspberry Pi GPIO Speed,其測試結果如下表所示
#!/usr/bin/pythonimport thread
import time
# Define a function for the threaddef print_time( threadName, delay):
count =0while count <5:
time.sleep(delay)
count +=1print"%s: %s"%( threadName, time.ctime(time.time()))# Create two threads as followstry:
thread.start_new_thread( print_time,("Thread-1",2,))
thread.start_new_thread( print_time,("Thread-2",4,))except:print"Error: unable to start thread"while1:pass
使用下面的method 同步thread
(1)Lock() method: returns the new lock.
(2)Racquire(blocking) method :force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.
(3)release() method of the new lock object is used to release the lock when it is no longer required.
Example
#!/usr/bin/pythonimport threading
import time
class myThread (threading.Thread):def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)self.threadID = threadID
self.name = name
self.counter = counter
def run(self):print"Starting "+self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name,self.counter,3)# Free lock to release next thread
threadLock.release()def print_time(threadName, delay, counter):while counter:
time.sleep(delay)print"%s: %s"%(threadName, time.ctime(time.time()))
counter -=1
threadLock = threading.Lock()
threads =[]# Create new threads
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",2)# Start new Threads
thread1.start()
thread2.start()# Add threads to thread list
threads.append(thread1)
threads.append(thread2)# Wait for all threads to completefor t in threads:
t.join()print"Exiting Main Thread"
#!/usr/bin/env python2.7
# demo of "BOTH" bi-directional edge detection
import RPi.GPIO as GPIO
from time import sleep # this lets us have a time delay (see line 12)
GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering
GPIO.setup(25, GPIO.IN) # set GPIO25 as input (button)
# Define a threaded callback function to run in another thread when events are detected
def my_callback(channel):
if GPIO.input(25): # if port 25 == 1
print "Rising edge detected on 25"
else: # if port 25 != 1
print "Falling edge detected on 25"
# when a changing edge is detected on port 25, regardless of whatever
# else is happening in the program, the function my_callback will be run
GPIO.add_event_detect(25, GPIO.BOTH, callback=my_callback)
print "Program will finish after 30 seconds or if you press CTRL+C\n"
print "Make sure you have a button connected, pulled down through 10k resistor"
print "to GND and wired so that when pressed it connects"
print "GPIO port 25 (pin 22) to GND (pin 6) through a ~1k resistor\n"
print "Also put a 100 nF capacitor across your switch for hardware debouncing"
print "This is necessary to see the effect we're looking for"
raw_input("Press Enter when ready\n>")
class MyThread(Thread):
def ___init__(self, condition):
Thread.__init__(self)
self.cond = condition
def run(self):
print '{0} start\r\n'.format(self.getName())
global cnt
while (True): id = threadPool.get()
if id != None:
self.cond.acquire()
print '{0}_{1}'.format(self.getName(), id)
for x in xrange(101):
cnt += x
time.sleep(2)
print 'cnt = {0}\r\n'.format(cnt)
cnt = 0
self.cond.release()
threadPool.task_done()
threadPool = Queue.Queue(0)
condition = Condition()
cnt = 0
for i in xrange(2):
MyThread(condition).start()
First approaches to image processing: load and display an image
import cv2 as cv
img = cv.imread('logos.jpg') # imread () method reads the file (a compressed format such as JPG) and translate it into a data structure # made of numerical matrix corresponding to color gradations and position. cv.imshow('Image', img) # imshow()method to create a window with the image loaded in the variable img cv.waitKey(0) #waitKey() method starts the display of a window and also allows you to control the waiting time of the program before continuing with the next command
Working with images
import cv2 ascv
img=cv.imread('logos.jpg')
b,r,g=cv.split(img)
img2=cv.merge((b,g,r))
cv.imshow('Image',img)
cv.imshow('Image2',img2)
cv.waitKey(0)
cv.destroyAllWindows()
After loading the image Decompose in the three RGB channels. You can do this easily by using the split() method. Now reassemble the three channels, but changing the order, for example by exchanging the red channel with the green channel. You can easily make recombination using the merge() method. The destroyWindow() method allows you to close the desired window (could be several open) by specifying as argument the name of the window which in your case is “Image”.
Save the new image
cv.imwrite('newlogos.png',img2)
Accessing and Modifying pixel values
You can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green, Red values. For grayscale image, just corresponding intensity is returned.
px=img[100,100]printpx[157 166 200]# accessing only blue pixelblue=img[100,100,0]printblue157
Image properties include number of rows, columns and channels, type of image data, number of pixels etc. Shape of image is accessed by img.shape. It returns a tuple of number of rows, columns and channels (if image is color):
Example : rows,cols,channels=img2.shape
printimg.shape (342, 548, 3)
Note
If image is grayscale, tuple returned contains only number of rows and columns. So it is a good method to check if loaded image is grayscale or color image.
Total number of pixels is accessed by img.size:
>>> printimg.size562248
Image datatype is obtained by img.dtype:
>>> printimg.dtypeuint8
Image ROI
Sometimes, you will have to play with certain region of images. ROI is again obtained using Numpy indexing. Here I am selecting the ball and copying it to another region in the image:
The B,G,R channels of an image can be split into their individual planes when needed. Then, the individual channels can be merged back together to form a BGR image again. This can be performed by:
b,g,r=cv2.split(img)img=cv2.merge((b,g,r))
Or
b=img[:,:,0]
Suppose, you want to make all the red pixels to zero, you need not split like this and put it equal to zero. You can simply use Numpy indexing which is faster. img[:,:,2]=0
Making Borders for Images (Padding)
If you want to create a border around the image, something like a photo frame, you can use cv2.copyMakeBorder() function. But it has more applications for convolution operation, zero padding etc. This function takes following arguments:
src - input image
top, bottom, left, right - border width in number of pixels in corresponding directions
borderType - Flag defining what kind of border to be added. It can be following types:
cv2.BORDER_CONSTANT - Adds a constant colored border. The value should be given as next argument.
cv2.BORDER_REFLECT - Border will be mirror reflection of the border elements, like this : fedcba|abcdefgh|hgfedcb
cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT - Same as above, but with a slight change, like this : gfedcb|abcdefgh|gfedcba
cv2.BORDER_REPLICATE - Last element is replicated throughout, like this: aaaaaa|abcdefgh|hhhhhhh
cv2.BORDER_WRAP - Can’t explain, it will look like this : cdefgh|abcdefgh|abcdefg
value - Color of border if border type is cv2.BORDER_CONSTANT
Below is a sample code demonstrating all these border types for better understanding:
Learn several arithmetic operations on images like addition, subtraction, bitwise operations etc.
You will learn these functions : cv2.add(), cv2.addWeighted() etc.
Image Addition
You can add two images by OpenCV function, cv2.add() or simply by numpy operation, res=img1+img2. Both images should be of same depth and type, or second image can just be a scalar value.
Image Blending
This is also image addition, but different weights are given to images so that it gives a feeling of blending or transparency. Images are added as per the equation below:
cv2.addWeighted() applies following equation on the image.
More info .... https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_image_arithmetics/py_image_arithmetics.html
Bitwise Operations
This includes bitwise AND, OR, NOT and XOR operations. They will be highly useful while extracting any part of the image , defining and working with non-rectangular ROI etc.
Installing collected packages: numpy, opencv-python Found existing installation: numpy 1.8.1 DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling numpy-1.8.1: Successfully uninstalled numpy-1.8.1 Successfully installed numpy-1.13.3 opencv-python-3.3.0.10
(4)測試模組
c:\python> python
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> print cv2.__version__ 3.3.0 >>> import numpy >>> print numpy.__version__ 1.13.3 >>>
在Web的世界中, client 和 server 兩者之間最常做的動作就是 Request-Response(要求-回應),用戶端送一個要求(Request),而伺服器回應訊息(Response)。 所以我們要了解HTTP Request的方法。HTTP Request 的方法有二種: GET and POST,這二者之間有何差別。
<script src="{% static "jquery-3.2.1.js" %}"></script> <script src="{% static "jquery-ui-1.12.1.zip" %}"></script> <! ------- must care the path --------------------------------------------!> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"> </script> <script type="text/javascript">
function list_Btn() { var list = $('#right').text(); alert(list);
$.ajax({ url: '/list_ret/', type: 'get', data :{'list' : list}, success: function(msg) { alert('結果'+msg); }, error: function(data){ alert('status:'+data.status); // the status code alert(data.responseJSON.error); // the message } }); } </script> </head>
<div id = 'right' style="width: 25%; float:right;text-align:left;font-size:20px;"> 資料傳送開始 <br> <input id = 'song_Btn' type ="button" value="傳送" onClick="list_Btn()"></input> </div>
</html>
新增list_ret.html
傳送資料回覆(任何傳送前端內容) {{list_ret_data}}
這是一個最簡單的一個範例,我們可以在 class list_ret 中接收到前端所傳送過來的所有資料,然後我們就可以在後端做資料庫處理,作檔案操縱,作企業邏輯運算,作任何在後端可以做的事,運算完後將結果放入一個中間網頁再回傳到原來呼叫的網頁,如此就可以不用改變前端網頁內容而做到後端處理的非同步網頁處理方式。