OpenCV-代码简单实践
import cv2
print("Package imported")
img = cv2.imread("img/test.jpg")
cv2.imshow("output",img)
cv2.waitKey(0)
import cv2
cap = cv2.VideoCapture("img/20210318.mp4")
while True:
success, img = cap.read()
cv2.imshow("Vidio",img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,640)
while True:
success, img = cap.read()
cv2.imshow("Vidio",img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
import cv2
import numpy as np
img = cv2.imread("img/test.jpg")
kernel = np.ones((5,5),np.uint8)
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(9,9),10)
imgCanny = cv2.Canny(img, 100, 200)
imgDialation = cv2.dilate(imgCanny,kernel,iterations=2)
imgEroded = cv2.erode(imgDialation,kernel,iterations=2)
cv2.imshow("Gray Image", imgGray)
cv2.imshow("Blur Image", imgBlur)
cv2.imshow("Canny1 Image", imgCanny)
cv2.imshow("Dialation Image", imgDialation)
cv2.imshow("Eroded Image", imgEroded)
cv2.waitKey(0)
import cv2
import numpy as np
img = cv2.imread("img/test.jpg")
print(img.shape)
imgResize = cv2.resize(img,(300,200))
imgCropped = img[0:500,0:500]
cv2.imshow("img",img)
cv2.imshow("imgResize",imgResize)
cv2.imshow("imgCropped",imgCropped)
cv2.waitKey(0)
import cv2
import numpy as np
img = np.zeros((512,512,3),np.uint8)
print(img)
cv2.line(img,(0,0),(300,300),(0,255,0),3)
cv2.rectangle(img,(0,0),(250,350),(0,0,255),2)
cv2.circle(img,(400,50),30,(255,0,0),5)
cv2.putText(img,"OPENCV",(300,100),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0),1)
cv2.imshow("Image",img)
cv2.waitKey(0)
import cv2
import numpy as np
img = cv2.imread("img/test.jpg")
width,height = 250,350
pts1 = np.float32([[111,219],[287,118],[154,482],[352,440]])
pts2 = np.float32([[0,0],[width,0],[0,height],[width,height]])
matrix = cv2.getPerspectiveTransform(pts1,pts2)
imgOutput = cv2.warpPerspective(img,matrix,(width,height))
cv2.imshow("Image",img)
cv2.imshow("ImgOutput",imgOutput)
cv2.waitKey(0)
import cv2
import numpy as np
img = cv2.imread("img/test.jpg")
imghor = np.hstack((img,img))
imgVer = np.vstack((img,img))
cv2.imshow("Imahor",imghor)
cv2.imshow("ImaVer",imgVer)
cv2.waitKey(0)
import cv2
import numpy as np
def empty(a):
pass
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)
cv2.createTrackbar("Hue Min","TrackBars",0,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",179,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",0,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",255,255,empty)
cv2.createTrackbar("Val Min","TrackBars",0,255,empty)
cv2.createTrackbar("Val Max","TrackBars",255,255,empty)
while True:
img = cv2.imread("img/test.jpg")
imgHSV = cv2.cvtColor(img,cv2.COLOR_HSV2BGR)
h_min = cv2.getTrackbarPos("Hue Min","TrackBars")
h_max = cv2.getTrackbarPos("Hue Max","TrackBars")
s_min = cv2.getTrackbarPos("Sat Min","TrackBars")
s_max = cv2.getTrackbarPos("Sat Max","TrackBars")
v_min = cv2.getTrackbarPos("Val Min","TrackBars")
v_max = cv2.getTrackbarPos("Val Max","TrackBars")
lower = np.array([h_min,s_min,v_min])
upper = np.array([h_max,s_max,v_max])
mask = cv2.inRange(imgHSV,lower,upper)
imgResult = cv2.bitwise_and(img,img,mask=mask)
cv2.imshow("Image",img)
cv2.imshow("ImgHSV",imgHSV)
cv2.imshow("Mask",mask)
cv2.imshow("imgResult",imgResult)
cv2.waitKey(1)
import cv2
import numpy as np
def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
else:
imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
imageBlank = np.zeros((height, width, 3), np.uint8)
hor = [imageBlank]*rows
hor_con = [imageBlank]*rows
for x in range(0, rows):
hor[x] = np.hstack(imgArray[x])
ver = np.vstack(hor)
else:
for x in range(0, rows):
if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
else:
imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
hor= np.hstack(imgArray)
ver = hor
return ver
def getCountours(img):
countours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cnt in countours:
area = cv2.contourArea(cnt)
print(area)
if area > 500:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt,True)
approx= cv2.approxPolyDP(cnt,0.02*peri,True)
print(approx)
objCor = len(approx)
x, y, w, h = cv2.boundingRect(approx)
ObjeactType = "None"
if objCor == 3:
ObjeactType = "Tri"
cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(imgContour,ObjeactType,
(x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,1,
(0,255,0),1)
path = "img/test.jpg"
img = cv2.imread(path)
imgContour = img.copy()
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(7,7),1)
imgCanny = cv2.Canny(imgBlur,50,50)
getCountours(imgCanny)
imgBlack = np.zeros_like(img)
imgStack = stackImages(0.6,([img,imgGray,imgBlur],
[imgCanny,imgContour,imgBlack]))
cv2.imshow("imgStack",imgStack)
cv2.waitKey(0)
import cv2
faceCascade = cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml")
img = cv2.imread("Resources/lena.png")
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(imgGray,1.1,4)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow("img",img)
cv2.waitKey(0)
import cv2
import numpy as np
import time
widthImg = 640
heightImg = 480
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3,frameWidth)
cap.set(4,frameHeight)
cap.set(10,150)
def perProcessing(img):
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(5,5),1)
imgCanny = cv2.Canny(imgBlur,200,200)
kernel = np.ones((5,5))
imgDial = cv2.dilate(imgCanny,kernel,iterations=2)
imgThres = cv2.erode(imgDial,kernel,iterations=1)
return imgThres
def getCountours(img):
biggest = np.array([])
maxArea = 0
contours, hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area>5000:
peri = cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,0.02*peri,True)
if area > maxArea and len(approx) == 4:
biggest = approx
maxArea = area
cv2.drawContours(img, biggest, -1, (255, 0, 0), 20)
return biggest
def reorder(myPoints):
myPoints = myPoints.reshape((4, 2))
myPointsNew = np.zeros((4, 1, 2), np.int32)
add =myPoints.sum(1)
myPointsNew[0] = myPoints[np.argmin(add)]
myPointsNew[3] = myPoints[np.argmax(add)]
diff = np.diff(myPoints,axis=1)
myPointsNew[1] = myPoints[np.argmin(diff)]
myPointsNew[2] = myPoints[np.argmax(diff)]
return myPointsNew
def getWarp(img, biggest):
biggest = reorder(biggest)
print(biggest)
pts1 = np.float32(biggest)
pts2 = np.float32([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]])
matrix = cv2.getPerspectiveTransform(pts1, pts2)
imgOutPut = cv2.warpPerspective(img, matrix, (widthImg, heightImg))
imgCropped = imgOutPut[20:imgOutPut.shape[0]-20, 20:imgOutPut.shape[1]-20]
imgCropped = cv2.resize(imgCropped,(widthImg,heightImg))
return imgCropped
while True:
success,img = cap.read()
cv2.resize(img, (widthImg, heightImg))
imgCount = img.copy()
imgThres = perProcessing(img)
biggest = getCountours(imgThres)
if biggest.size != 0:
imgWarped = getWarp(img, biggest)
cv2.imshow("result",imgWarped)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
import cv2
import numpy as np
nPlateCascade = cv2.CascadeClassifier("Resources/haarcascade_russian_plate_number.xml")
minArea = 500
color = (255, 0, 255)
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
cap.set(10,130)
count = 0
while True:
success, img = cap.read()
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
numberPlates = nPlateCascade.detectMultiScale(imgGray, 1.1 ,4)
for (x, y, w, h) in numberPlates:
area = w*h
if area > minArea:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(img, "Number Plate", (x, y-5),
cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, color, 2)
imgRoi = img[y:y+h, x:x+w]
cv2.imshow("ROI",imgRoi)
cv2.imshow("Result",img)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.imwrite("Resources/Scanned/NoPlate_",str(count) + ".jpg",imgRoi)
cv2.rectangle(img, (0, 200), (640, 300), (0, 255, 0), cv2.FILLED)
cv2.putText(img, "Scan Saved", (150, 265), cv2.FONT_HERSHEY_COMPLEX_SMALL,
2, (0, 0, 255), 2)
cv2.imshow("Result", img)
cv2.waitKey(500)
count += 1