《OpenCV图像处理(Python)》网课笔记(从1到4)

1. Intro and loading images( 介绍和加载图像)

代码部分


# coding: utf-8

# In[4]:


#lesson 1


# In[5]:


import cv2
import numpy as np
import matplotlib.pyplot as plt


# In[6]:


img = cv2.imread('template.png',cv2.IMREAD_GRAYSCALE)


# In[7]:


#IMREAD_GRAYSCALE = 0
#IMREAD_COLOR     = 1
#IMREAD_UNCHANGED = -1


# In[9]:


cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


# In[13]:


# method 2 for show pictures
# plt.imshow(img,cmap='gray',interpolation='bicubic')

# #draw a line on the picture
# plt.plot([800,1000],[200,500],'c',linewidth=5)
# plt.show()


# In[14]:


cv2.imwrite('output.png',img)

其中,template.png

output.png

 2. Loading video source(加载视频资源)

代码


# coding: utf-8

# In[1]:


#lesson2


# In[2]:


import cv2
import numpy as np


# In[12]:


cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('lesson2.avi',fourcc,20.0,(640,480))

while True:
    ret, frame = cap.read()
    if ret is True: 
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
    else:   
        break

    out.write(frame)
    cv2.imshow('frame',frame)
    cv2.imshow('gray',gray)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
        
cap.release()
out.release()
cv2.destroyAllWindows()

3. Drawing and writing on images (在图像上画图和写字)

代码部分


# coding: utf-8

# In[27]:


#lesson3


# In[28]:


import numpy as np
import cv2


# In[29]:


img = cv2.imread('template.png',cv2.IMREAD_COLOR)


# In[30]:


cv2.line(img,(0,0),(500,150),(255,255,255),15)
cv2.rectangle(img,(15,25),(200,150),(0,255,0),5)
cv2.circle(img,(100,63),70,(0,0,255),-1)

pts = np.array([[110,105],[120,140],[170,120],[180,110]],np.int32)
# pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(0,255,255),8)

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV Tuts!',(200,300),font,1,(200,0,0),5,cv2.LINE_AA)

cv2.imwrite('lesson3.png',img)

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出的lesson3.png

4. Image operations (图像运算)

代码


# coding: utf-8

# In[13]:


#leeson4


# In[37]:


import numpy as np
import cv2


# In[38]:


img = cv2.imread('template.png',cv2.IMREAD_COLOR)


# In[39]:


# img[55,55] = [255,255,255]
# px = img[55,55]
# print(px)


# In[40]:


# ROI: region of interest
roi = img[100:200,100:200]
print(roi)


# In[42]:


# img[100:200,100:200] = [255,255,255]

copy_part = img[337:500,307:394]
img[0:163,0:87] = copy_part

cv2.imwrite('lesson4.png',img)

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 输出结果lesson4.png

你可能感兴趣的:(图像处理)