OpenCV 简单入门| Python - 图1
© OpenCV

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Install

  1. pip3 install --upgrade setuptools
  2. pip3 install numpy Matplotlib
  3. pip3 install opencv-python

Img Read and Show

Load an color image in grayscale

  1. import numpy as np
  2. import cv2
  3. img = cv2.imread('messi5.jpg',0)

img read from Camera

  1. cap = cv2.VideoCapture(0)
  2. ret, frame = cap.read()
  3. cap.release()
  4. cap = cv2.VideoCapture(0)
  5. while(True):
  6. ret, frame = cap.read()
  7. cv2.imshow('image',frame)
  8. if cv2.waitKey(1) & 0xFF == ord('q'):
  9. cv2.destroyAllWindows()
  10. break

Resolution of the img

  1. cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280)
  2. cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720)

img show and close

  1. cv2.imshow('image',img)
  2. if cv2.waitKey(0) & 0xFF == ord('q'):
  3. cv2.destroyAllWindows()

resize

  1. cv2.resize(img, (10,10), interpolation = cv2.INTER_AREA)

img wirte

  1. cv2.imwrite('messigray.png',img)

img to gif

Original Webpage:

  1. import cv2
  2. import imageio
  3. List = ['./yang1.jpg', './yang2.jpg', './yang3.jpg']
  4. frames = []
  5. for img in List:
  6. img = cv2.imread(img, 1)
  7. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  8. img = cv2.resize(img, (460,360))
  9. frames.append(img)
  10. gif=imageio.mimsave('yang.gif',frames,'GIF',duration=0.4)

Screen shot

  1. import cv2
  2. import numpy as np
  3. from mss import mss
  4. cords = {'top':40 , 'left': 0 , 'width': 800, 'height': 640 }
  5. while(True):
  6. with mss() as sct :
  7. img = np.array(sct.grab(cords)) #sct.grab(cords/monitor)
  8. #cimg = cv2.cvtColor(img , cv2.COLOR_BGRA2GRAY)
  9. cv2.imshow('image',img)
  10. if cv2.waitKey(1) & 0xFF == ord('q'):
  11. cv2.destroyAllWindows()
  12. break
  13. cv2.destroyAllWindows()

Draw on Img

Draw a Rectangle

reference: AlanWang4523 2018

  1. ## 绘制一个红色矩形
  2. ptLeftTop = (120, 100)
  3. ptRightBottom = (200, 150)
  4. point_color = (0, 0, 255) # BGR
  5. thickness = 1
  6. lineType = 8
  7. cv.rectangle(img, ptLeftTop, ptRightBottom, point_color, thickness, lineType)

Write on the image

  1. img = cv2.imread('messi5.jpg',0)
  2. cv2.putText(img, "Hello World" ,(200, 100), cv2.FONT_HERSHEY_COMPLEX, 2.0, (100, 200, 200), 5)

Other Tricks for image

  1. ## Blur
  2. img = cv2.medianBlur(img,5)
  3. ## Grey
  4. cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)

Video

Video read

  1. cap=cv2.VideoCapture("test")
  2. while (True):
  3. ret,frame=cap.read()
  4. cv2.imshow("video",frame)
  5. # 在播放每一帧时,使用cv2.waitKey()设置适当的持续时间。如果设置的太低视频就会播放的非常快,如果设置的太高就会播放的很慢。通常情况下25ms就ok
  6. if cv2.waitKey(25)&0xFF==ord('q'):
  7. cv2.destroyAllWindows()
  8. break

Reading Video information

  1. ## fps of this Video
  2. fps_c = cap.get(cv2.CAP_PROP_FPS)
  3. frame _total = cap.get(cv2.CAP_PROP_FRAME_COUNT)
  4. Video_h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
  5. Video_w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)

play Video and audio

  1. ##https://stackoverflow.com/questions/46864915/python-add-audio-to-video-opencv
  2. import cv2
  3. import numpy as np
  4. ##ffpyplayer for playing audio
  5. from ffpyplayer.player import MediaPlayer
  6. video_path="../L1/images/Godwin.mp4"
  7. def PlayVideo(video_path):
  8. video=cv2.VideoCapture(video_path)
  9. player = MediaPlayer(video_path)
  10. while True:
  11. grabbed, frame=video.read()
  12. audio_frame, val = player.get_frame()
  13. if not grabbed:
  14. print("End of video")
  15. break
  16. if cv2.waitKey(28) & 0xFF == ord("q"):
  17. break
  18. cv2.imshow("Video", frame)
  19. if val != 'eof' and audio_frame is not None:
  20. #audio
  21. img, t = audio_frame
  22. video.release()
  23. cv2.destroyAllWindows()
  24. PlayVideo(video_path)

Video write

  1. ## for normal output
  2. fourcc = cv2.VideoWriter_fourcc(*'XVID')
  3. out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
  4. while true:
  5. out.write(frame)
  6. ## For Gray outpu
  7. fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
  8. out = cv2.VideoWriter("outfilename.mp4", fourcc, 15, (640,480), 0)

Img to Video

  1. import cv2, os
  2. File = "Up"
  3. OUTPUT = "Egg_Day1.avi"
  4. List = os.popen('ls '+File).read().split('\n')[:-1]
  5. img = cv2.imread(File +"/"+List[0])
  6. fps = 24
  7. size = (len(img[0]),len(img))
  8. fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
  9. videowriter = cv2.VideoWriter(OUTPUT,fourcc,fps,size)
  10. for i in List:
  11. img = cv2.imread(File +"/"+i)
  12. videowriter.write(img)
  13. videowriter.release()

vedio to gif

  1. from cv2 import cv2
  2. import imageio
  3. import numpy
  4. # Collection of the imgs
  5. frames_list = []
  6. # Tossed frames per FPS. When FPS = 1, all frame are saved.
  7. FPS = 1
  8. cap=cv2.VideoCapture("test_1.mp4")
  9. while (True):
  10. ret,frame=cap.read()
  11. #img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  12. img = cv2.resize(frame, (460,360))
  13. frames_list.append(img)
  14. frames = []
  15. Num =0
  16. for img in frames_list:
  17. Num +=1
  18. if Num %3 == 0:
  19. frames.append(img)
  20. gif=imageio.mimsave('test_3.gif',frames,'GIF',duration=1/8)

Video capture

  1. ##!/usr/bin/env python
  2. ## -*- coding: utf-8 -*-
  3. ## @Time : 2019/3/7 11:43
  4. ## @Author : HaoWANG
  5. ## @Site :
  6. ## @File : VideoWrite.py
  7. ## @Software: PyCharm
  8. ## 加载包
  9. import math
  10. import sys
  11. import cv2
  12. def main():
  13. # 初始化摄像头
  14. keep_processing = True;
  15. camera_to_use = 0; # 0 if you have one camera, 1 or > 1 otherwise
  16. cap = cv2.VideoCapture(0) # 定义视频捕获类cap
  17. windowName = "Live Video Capture and Write" # 窗口名
  18. # opencv中视频录制需要借助VideoWriter对象, 将从VideoCapture 中读入图片,不断地写入到VideoWrite的数据流中。
  19. # 指定视频编解码方式为MJPG
  20. codec = cv2.VideoWriter_fourcc(*'MJPG')
  21. fps = 25.0 # 指定写入帧率为25
  22. frameSize = (640, 480) # 指定窗口大小
  23. # # 创建 VideoWriter对象
  24. output = cv2.VideoWriter('VideoRecord.avi', codec, fps, frameSize)
  25. # 摄像头开启检测
  26. # error detection #
  27. if not (((len(sys.argv) == 2) and (cap.open(str(sys.argv[1]))))
  28. or (cap.open(camera_to_use))):
  29. print("ERROR:No video file specified or camera connected.")
  30. return -1
  31. # Camera Is Open
  32. # create window by name (note flags for resizable or not)
  33. cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
  34. print("按键Q-结束视频录制")
  35. while (cap.isOpened()):
  36. # 00 if video file successfully open then read frame from video
  37. if (keep_processing):
  38. ret, frame = cap.read() # 定义read对象ret和frame帧
  39. # start a timer (to see how long processing and display takes)
  40. start_t = cv2.getTickCount()
  41. # 不断的从VideoCapture 中读入图片,然后写入到VideoWrite的数据流中。
  42. output.write(frame)
  43. cv2.imshow(windowName, frame) # display image
  44. # stop the timer and convert to ms. (to see how long processing and display takes)
  45. stop_t = ((cv2.getTickCount() - start_t) / cv2.getTickFrequency()) * 1000
  46. # 接收键盘停止指令
  47. # start the event loop - essential
  48. # wait 40ms or less depending on processing time taken (i.e. 1000ms / 25 fps = 40 ms)
  49. key = cv2.waitKey(max(2, 40 - int(math.ceil(stop_t)))) & 0xFF
  50. # It can also be set to detect specific key strokes by recording which key is pressed
  51. # e.g. if user presses "q" then exit
  52. if (key == ord('q')):
  53. print("Quit Process ")
  54. keep_processing = False
  55. else:
  56. break
  57. print("The display and video write tasks take {} ms".format(stop_t))
  58. # release the camera and close all windows
  59. # 资源释放,在录制结束后,我们要释放资源:
  60. # # 释放资源
  61. cap.release()
  62. output.release()
  63. cv2.destroyAllWindows()
  64. ## end main()
  65. if __name__ == "__main__":
  66. main()

Training your personal model

  1. '''
  2. positive list:
  3. Pics in Me director, 55*110
  4. Background Pics are in BG file
  5. '''
  6. for i in $(ls Me/);do echo Me/$i 1 0 0 55 110;done > pos.list
  7. for i in $(ls BG/);do echo BG/$i;done > bg.list
  8. rm models/*
  9. opencv_createsamples -info pos.list -vec pos.vec -bg bg.list -num 12 -w 20 -h 40
  10. opencv_traincascade -data models/ -vec pos.vec -bg bg.list -numPos 12 -numNeg 27 -numStages 2 -featureType HAAR -w 20 -h 40
  11. '''
  12. s
  13. '''
  14. import cv2
  15. ## 探测图片中的人脸
  16. detector = cv2.CascadeClassifier("models/params.xml") # absolute !!!
  17. faces = detector.detectMultiScale(img)
  18. for(x,y,w,h) in faces:
  19. cv2.rectangle(image,(x,y),(x+w,y+w),(0,255,0),2)

Matlibplot

  1. ## -*- coding: utf-8 -*-
  2. """
  3. ## --------------------------------------------------------
  4. ## @Author : panjq
  5. ## @E-mail : pan_jinquan@163.com
  6. ## @Date : 2020-02-05 11:01:49
  7. ## --------------------------------------------------------
  8. """
  9. import matplotlib.pyplot as plt
  10. import numpy as np
  11. import cv2
  12. def fig2data(fig):
  13. """
  14. fig = plt.figure()
  15. image = fig2data(fig)
  16. @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
  17. @param fig a matplotlib figure
  18. @return a numpy 3D array of RGBA values
  19. """
  20. import PIL.Image as Image
  21. # draw the renderer
  22. fig.canvas.draw()
  23. # Get the RGBA buffer from the figure
  24. w, h = fig.canvas.get_width_height()
  25. buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
  26. buf.shape = (w, h, 4)
  27. # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
  28. buf = np.roll(buf, 3, axis=2)
  29. image = Image.frombytes("RGBA", (w, h), buf.tostring())
  30. image = np.asarray(image)
  31. return image
  32. if __name__ == "__main__":
  33. # Generate a figure with matplotlib</font>
  34. figure = plt.figure()
  35. plot = figure.add_subplot(111)
  36. # draw a cardinal sine plot
  37. x = np.arange(1, 100, 0.1)
  38. y = np.sin(x) / x
  39. plot.plot(x, y)
  40. plt.show()
  41. ##
  42. image = fig2data(figure)
  43. cv2.imshow("image", image)
  44. cv2.waitKey(0)

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗