1.图像处理基本使用
import cv2
image = cv2.imread("images/1.png", cv2.IMREAD_GRAYSCALE)
print("image:",image)
namedWindow = cv2.namedWindow("images/1.png")
cv2.imshow("images/1.png", image)
waitKey = cv2.waitKey(0)
print("waitKey:",waitKey)
if waitKey == ord('A') or waitKey == ord('a'):
print("you press the A or a")
destroyWindow = cv2.destroyWindow("images/1.png")
print("destroyWindow:",destroyWindow)
image = cv2.imread("images/1.png", cv2.IMREAD_COLOR)
print("image.shape:",image.shape)
px=image[100,100]
print("px=",px)
blue=image[100,100,0]
print("blue=",blue)
cv2.destroyAllWindows()
imwrite = cv2.imwrite("output/1_output.png", image)
print(imwrite)
2.图像处理基础
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = np.random.randint(0, 256, size=[500, 500, 3], dtype=np.uint8)
print("img=\n", img)
print("读取像素点img.item(3,2)=", img.item(3, 2, 1))
img.itemset((3, 2, 1), 255)
print("修改后img=\n", img)
print("修改后像素点img.item(3,2)=", img.item(3, 2, 1))
cv2.imshow("hh", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
a=cv2.imread("images/1.png",cv2.IMREAD_UNCHANGED)
print(a.shape)
face=a[60:160,60:160]
cv2.imshow("original",a)
cv2.imshow("face",face)
cv2.waitKey()
cv2.destroyAllWindows()
red_img=a[:,:,2]
cv2.imshow("red_img",red_img)
a[:,:,2]=0
cv2.imshow("nored_img", a)
cv2.waitKey(0)
cv2.destroyAllWindows()
b,g,r=cv2.split(a)
plt.figure()
plt.subplot(1,3,1)
plt.imshow(b)
plt.title("b", fontsize=8)
plt.xticks([])
plt.yticks([])
plt.subplot(1,3,2)
plt.imshow(g)
plt.title("g",fontsize=8)
plt.xticks([])
plt.yticks([])
plt.subplot(1,3,3)
plt.imshow(r)
plt.title("r",fontsize=8)
plt.xticks([])
plt.yticks([])
plt.show()
bgr=cv2.merge([b,g,r])
rgb=cv2.merge([r,g,b])
cv2.imshow("image",a)
cv2.imshow("bgr",bgr)
cv2.imshow("rgb",rgb)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
BLUE = [255,0,0]
img1=cv.imread("images/zlh.jpg",cv.IMREAD_COLOR)
replicate = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REPLICATE)
reflect = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT)
reflect101 = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT_101)
wrap = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_WRAP)
constant= cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show()
3.图像运算
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread("images/1.png")
r = np.random.randint(0, 255, (500, 500, 1), dtype=np.uint8)
g = np.random.randint(0, 255, (500, 500, 1), dtype=np.uint8)
b = np.random.randint(0, 255, (500, 500, 1), dtype=np.uint8)
res = r + g + b
cv2.imshow("b=g+r+a", res)
res = cv2.add(g, r, b)
cv2.imshow("b=cv2.add(g,r,a)", res)
cv2.waitKey(0)
merge = cv2.merge([b, g, r])
cv2.imshow("merge", merge)
cv2.waitKey(0)
addWeighted = cv2.addWeighted(r, 10, g, 3, 10)
cv2.imshow("addWeighted", addWeighted)
cv2.waitKey(0)
mask = np.zeros(image.shape, dtype=np.uint8)
mask[60:120, 10:70] = 255
mask[160:190, 80:190] = 255
bitwise_and = cv2.bitwise_and(image, mask)
cv2.imshow("bitwise_and", bitwise_and)
cv2.waitKey(0)
img1 = np.ones((4, 4), dtype=np.uint8) * 3
img2 = np.ones((4, 4), dtype=np.uint8) * 5
mask = np.zeros((4, 4), dtype=np.uint8)
mask[2:4, 2:4] = 1
img3 = np.ones((4, 4), dtype=np.uint8) * 66
print("img1=\n", img1)
print("img2=\n", img2)
print("mask=\n", mask)
print("初始值img3=\n", img3)
img3 = cv2.add(img1, img2, mask=mask)
print("求和后img3=\n", img3)
img1 = np.ones((4, 4), dtype=np.uint8) * 3
img2 = np.ones((4, 4), dtype=np.uint8) * 5
print("img1=\n", img1)
print("img2=\n", img2)
img3 = cv2.add(img1, img2)
print("cv2.add(img1,img2)=\n", img3)
img4 = cv2.add(img1, 6)
print("cv2.add(img1,6)\n", img4)
r, c = image.shape
x = np.zeros((r, c, 8), dtype=np.uint8)
for i in range(8):
x[:, :, i] = 2 ** i
r = np.zeros((r, c, 8), dtype=np.uint8)
for i in range(8):
r[:, :, i] = cv2.bitwise_and(image, x[:, :, i])
mask = r[:, :, i] > 0
r[mask] = 255
cv2.imshow(str(i), r[:, :, i])
cv2.waitKey(0)
img1 = cv2.imread('images/zlh.jpg')
img2 = cv2.imread('images/opencv-logo.png')
rows, cols, channels = img2.shape
roi = img1[0:rows, 0:cols]
print("roi:", roi)
img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
'''
threshold(src,thresh,maxval,type) type:指定阈值处理的类型。常见的类型包括:
cv2.THRESH_BINARY:像素值大于阈值的设为 maxval,否则设为0。
cv2.THRESH_BINARY_INV:像素值大于阈值的设为0,否则设为 maxval。
cv2.THRESH_TRUNC:像素值大于阈值的设为阈值,否则不变。
cv2.THRESH_TOZERO:像素值大于阈值的不变,否则设为0。
cv2.THRESH_TOZERO_INV:像素值大于阈值的设为0,否则不变。
'''
mask_inv = cv2.bitwise_not(mask)
img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
img2_fg = cv2.bitwise_and(img2, img2, mask=mask)
dst = cv2.add(img1_bg, img2_fg)
img1[0:rows, 0:cols] = dst
plt.subplot(231),plt.imshow(mask,'gray'),plt.title('mask')
plt.subplot(232),plt.imshow(mask_inv,'gray'),plt.title('mask_inv')
plt.subplot(233),plt.imshow(img1_bg,'gray'),plt.title('img1_bg')
plt.subplot(234),plt.imshow(img2_fg,'gray'),plt.title('img2_fg')
plt.subplot(235),plt.imshow(dst,'gray'),plt.title('dst')
plt.subplot(236),plt.imshow(img1,'gray'),plt.title('res')
plt.show()
r, c, channel = image.shape
key = np.random.randint(0, 256, size=[r, c, channel], dtype=np.uint8)
encryption = cv2.bitwise_xor(image, key)
decryption = cv2.bitwise_xor(encryption, key)
cv2.imshow("image", image)
cv2.imshow("key", key)
cv2.imshow("encryption", encryption)
cv2.imshow("decryption", decryption)
cv2.waitKey(0)
lena = cv2.imread("images/lena.bmp", 0)
watermark = cv2.imread("images/watermark.bmp", 0)
w = watermark[:, :] > 0
watermark[w] = 1
r, c = lena.shape
t254 = np.ones((r, c), dtype=np.uint8) * 254
lenaH7 = cv2.bitwise_and(lena, t254)
e = cv2.bitwise_or(lenaH7, watermark)
t1 = np.ones((r, c), dtype=np.uint8)
wm = cv2.bitwise_and(e, t1)
print(wm)
w = wm[:, :] > 0
wm[w] = 255
cv2.imshow("lena", lena)
cv2.imshow("watermark", watermark * 255)
cv2.imshow("e", e)
cv2.imshow("wm", wm)
cv2.waitKey()
lena = cv2.imread("images/lena.bmp", 0)
r, c = lena.shape
mask = np.zeros((r, c), dtype=np.uint8)
mask[220:400, 250:350] = 1
key = np.random.randint(0, 256, size=[r, c], dtype=np.uint8)
lenaXorKey = cv2.bitwise_xor(lena, key)
encryptFace = cv2.bitwise_and(lenaXorKey, mask * 255)
noFace1 = cv2.bitwise_and(lena, (1 - mask) * 255)
maskFace = encryptFace + noFace1
extractOriginal = cv2.bitwise_xor(maskFace, key)
extractFace = cv2.bitwise_and(extractOriginal, mask * 255)
noFace2 = cv2.bitwise_and(maskFace, (1 - mask) * 255)
extractLena = noFace2 + extractFace
cv2.imshow("lena", lena)
cv2.imshow("mask", mask * 255)
cv2.imshow("1-mask", (1 - mask) * 255)
cv2.imshow("key", key)
cv2.imshow("lenaXorKey", lenaXorKey)
cv2.imshow("encryptFace", encryptFace)
cv2.imshow("noFace1", noFace1)
cv2.imshow("maskFace", maskFace)
cv2.imshow("extractOriginal", extractOriginal)
cv2.imshow("extractFace", extractFace)
cv2.imshow("noFace2", noFace2)
cv2.imshow("extractLena", extractLena)
cv2.waitKey()
cv2.destroyAllWindows()
4.色彩空间类型转换
import cv2
image = cv2.imread("images/1.png", cv2.IMREAD_GRAYSCALE)
namedWindow = cv2.namedWindow("images/1.png")
cv2.imshow("images/1.png",image)
waitKey=cv2.waitKey(0)
print(waitKey)
if waitKey ==ord('A') or waitKey ==ord('a'):
print("you press the A or a")
destroyWindow=cv2.destroyWindow("images/1.png")
print(destroyWindow)
cv2.destroyAllWindows()
imwrite=cv2.imwrite("output/1_output.png",image)
print(imwrite)
5.OpenCV中的图像处理
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
flags = [i for i in dir(cv) if i.startswith('COLOR_')]
print(flags)
cap = cv.VideoCapture(0)
while (1):
_, frame = cap.read()
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
blue_mask = cv.inRange(hsv, lower_blue, upper_blue)
lower_red1 = np.array([0, 50, 50])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([160, 50, 50])
upper_red2 = np.array([180, 255, 255])
red_mask1 = cv.inRange(hsv, lower_red1, upper_red1)
red_mask2 = cv.inRange(hsv, lower_red2, upper_red2)
red_mask = cv.bitwise_or(red_mask1, red_mask2)
lower_green = np.array([40, 50, 50])
upper_green = np.array([80, 255, 255])
green_mask = cv.inRange(hsv, lower_green, upper_green)
final_mask = cv.bitwise_or(blue_mask, cv.bitwise_or(red_mask, green_mask))
extracted_image = cv.bitwise_and(frame, frame, mask=final_mask)
cv.imshow('frame', frame)
cv.imshow('mask', final_mask)
cv.imshow('res', extracted_image)
k = cv.waitKey(5) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
green = np.uint8([[[0, 255, 0]]])
hsv_green = cv.cvtColor(green, cv.COLOR_BGR2HSV)
print(hsv_green)
img = cv.imread('images/zlh.jpg')
res = cv.resize(img, None, fx=0.2, fy=0.2, interpolation=cv.INTER_CUBIC)
height, width = img.shape[:2]
res2 = cv.resize(img, (1 * width, 1 * height), interpolation=cv.INTER_CUBIC)
cv.imshow('img', img)
cv.imshow('res', res)
cv.imshow('res2', res2)
cv.waitKey(0)
cv.destroyAllWindows()
img = cv.imread('images/zlh.jpg')
rows, cols, _ = img.shape
M = np.float32([[1, 0, 100], [0, 1, 50]])
res = cv.warpAffine(img, M, (cols, rows))
cv.imshow('img', res)
cv.waitKey(0)
cv.destroyAllWindows()
img = cv.imread('images/zlh.jpg')
rows, cols, _ = img.shape
M = cv.getRotationMatrix2D(((cols - 1) / 2.0, (rows - 1) / 2.0), 90,
1)
dst = cv.warpAffine(img, M, (cols, rows))
cv.imshow('dst', dst)
cv.waitKey(0)
cv.destroyAllWindows()
img = cv.imread('images/zlh.jpg')
rows, cols, ch = img.shape
pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv.getAffineTransform(pts1, pts2)
dst = cv.warpAffine(img, M, (cols, rows))
plt.figure("放射变换")
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()
img = cv.imread('images/zlh.jpg')
rows, cols, ch = img.shape
pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
M = cv.getPerspectiveTransform(pts1, pts2)
dst = cv.warpPerspective(img, M, (300, 300))
plt.figure("透视变换")
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()
img = cv.imread('images/gradient.png', 0)
ret, thresh1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
ret, thresh2 = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
ret, thresh3 = cv.threshold(img, 127, 255, cv.THRESH_TRUNC)
ret, thresh4 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO)
ret, thresh5 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO_INV)
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
plt.figure("简单阈值")
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
image = cv.imread('images/shudu.png', 0)
blockSize = 11
C = 2
MEAN = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, blockSize, C)
GAUSSIAN = cv.adaptiveThreshold(image, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, blockSize, C)
_, THRESH_BINARY = cv.threshold(image, 127, 255, cv.THRESH_BINARY)
plt.subplot(221), plt.imshow(image, "gray"), plt.title('image')
plt.subplot(222), plt.imshow(MEAN, "gray"), plt.title('MEAN')
plt.subplot(223), plt.imshow(GAUSSIAN, "gray"), plt.title('GAUSSIAN')
plt.subplot(224), plt.imshow(THRESH_BINARY, "gray"), plt.title('THRESH_BINARY')
plt.show()
cv.waitKey(0)
cv.destroyAllWindows()
img = cv.imread('images/noisy.png', 0)
rows, cols = img.shape
noise = np.random.normal(0, 25, (rows, cols)).astype(np.uint8)
img = cv.add(img, noise)
ret1, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
ret2, th2 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
blur = cv.GaussianBlur(img, (5, 5), 0)
ret3, th3 = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
images = [img, 0, th1,
img, 0, th2,
blur, 0, th3]
titles = ['Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)',
'Original Noisy Image', 'Histogram', "Otsu's Thresholding",
'Gaussian filtered Image', 'Histogram', "Otsu's Thresholding"]
for i in range(3):
plt.subplot(3, 3, i * 3 + 1), plt.imshow(images[i * 3], 'gray')
plt.title(titles[i * 3]), plt.xticks([]), plt.yticks([])
plt.subplot(3, 3, i * 3 + 2), plt.hist(images[i * 3].ravel(), 256)
plt.title(titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
plt.subplot(3, 3, i * 3 + 3), plt.imshow(images[i * 3 + 2], 'gray')
plt.title(titles[i * 3 + 2]), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/opencv-logo.png')
kernel = np.ones((5, 5), np.float32) / 25
dst = cv.filter2D(img, -1, kernel)
plt.figure("2D卷积(图像过滤)")
plt.subplot(121), plt.imshow(img), plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(dst), plt.title('Averaging')
plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/opencv-logo.png')
rows, cols, ch = img.shape
noise = np.random.normal(0, 25, (rows, cols, ch)).astype(np.uint8)
img = cv.add(img, noise)
blur = cv.blur(img, (5, 5))
GaussianBlur = cv.GaussianBlur(img, (5, 5), 0)
medianBlur = cv.medianBlur(img, 5)
bilateralFilter = cv.bilateralFilter(img, 9, 150, 150)
plt.subplot(231), plt.imshow(img), plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(232), plt.imshow(blur), plt.title('blur')
plt.xticks([]), plt.yticks([])
plt.subplot(233), plt.imshow(GaussianBlur), plt.title('GaussianBlur')
plt.xticks([]), plt.yticks([])
plt.subplot(234), plt.imshow(medianBlur), plt.title('medianBlur')
plt.xticks([]), plt.yticks([])
plt.subplot(235), plt.imshow(bilateralFilter), plt.title('bilateralFilter')
plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/j.png', 0)
kernel = np.ones((5, 5), np.uint8)
erosion = cv.erode(img, kernel, iterations=1)
dilation = cv.dilate(img, kernel, iterations=1)
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
gradient = cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel)
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)
blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)
plt.subplot(241), plt.imshow(erosion), plt.title('erosion侵蚀')
plt.xticks([]), plt.yticks([])
plt.subplot(242), plt.imshow(dilation), plt.title('dilation扩张')
plt.xticks([]), plt.yticks([])
plt.subplot(243), plt.imshow(opening), plt.title('opening开运算')
plt.xticks([]), plt.yticks([])
plt.subplot(244), plt.imshow(closing), plt.title('closing闭运算')
plt.xticks([]), plt.yticks([])
plt.subplot(245), plt.imshow(gradient), plt.title('gradient形态学梯度')
plt.xticks([]), plt.yticks([])
plt.subplot(246), plt.imshow(tophat), plt.title('tophat顶帽')
plt.xticks([]), plt.yticks([])
plt.subplot(247), plt.imshow(tophat), plt.title('blackhat黑帽')
plt.xticks([]), plt.yticks([])
plt.subplot(248), plt.imshow(img), plt.title('img原图')
plt.xticks([]), plt.yticks([])
plt.show()
kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
print(kernel)
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
print(kernel)
kernel = cv.getStructuringElement(cv.MORPH_CROSS, (5, 5))
print(kernel)
img = cv.imread('images/shudu.png', 0)
laplacian = cv.Laplacian(img, cv.CV_64F)
sobelx = cv.Sobel(img, cv.CV_64F, 1, 0, ksize=5)
sobely = cv.Sobel(img, cv.CV_64F, 0, 1, ksize=5)
plt.subplot(2, 2, 1), plt.imshow(img, cmap='gray'), plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 2), plt.imshow(laplacian, cmap='gray'), plt.title('Laplacian'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 3), plt.imshow(sobelx, cmap='gray'), plt.title('Sobel X'), plt.xticks([]), plt.yticks([])
plt.subplot(2, 2, 4), plt.imshow(sobely, cmap='gray'), plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])
plt.show()
sobelx8u = cv.Sobel(img, cv.CV_8U, 1, 0, ksize=5)
sobelx64f = cv.Sobel(img, cv.CV_64F, 1, 0, ksize=5)
abs_sobel64f = np.absolute(sobelx64f)
sobel_8u = np.uint8(abs_sobel64f)
plt.subplot(1, 3, 1), plt.imshow(img, cmap='gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 3, 2), plt.imshow(sobelx8u, cmap='gray')
plt.title('Sobel CV_8U'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 3, 3), plt.imshow(sobel_8u, cmap='gray')
plt.title('Sobel abs(CV_64F)'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/shudu.png', 0)
threshold1 = 100
threshold2 = 200
apertureSize = 3
L2gradient = False
edges = cv.Canny(img, threshold1, threshold2, apertureSize, L2gradient=L2gradient)
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(edges, cmap='gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()
A = cv.imread('images/Apple.png')
B = cv.imread('images/Orange.png')
G = A.copy()
gpA = [G]
for i in range(6):
G = cv.pyrDown(G)
gpA.append(G)
G = B.copy()
gpB = [G]
for i in range(6):
G = cv.pyrDown(G)
gpB.append(G)
lpA = [gpA[5]]
for i in range(5, 0, -1):
GE = cv.pyrUp(gpA[i])
L = cv.subtract(gpA[i - 1], GE)
lpA.append(L)
lpB = [gpB[5]]
for i in range(5, 0, -1):
GE = cv.pyrUp(gpB[i])
L = cv.subtract(gpB[i - 1], GE)
lpB.append(L)
LS = []
for la, lb in zip(lpA, lpB):
rows, cols, dpt = la.shape
ls = np.hstack((la[:, 0:cols / 2], lb[:, cols / 2:]))
LS.append(ls)
ls_ = LS[0]
for i in range(1, 6):
ls_ = cv.pyrUp(ls_)
ls_ = cv.add(ls_, LS[i])
real = np.hstack((A[:, :cols / 2], B[:, cols / 2:]))
cv.imwrite('output/Pyramid_blending2.jpg', ls_)
cv.imwrite('output/Direct_blending.jpg', real)
img = cv.imread('images/Apple.png')
imggray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imggray, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
print(contours)
drawContours1 = cv.drawContours(img, contours, -1, (0, 255, 0), 3)
drawContours2 = cv.drawContours(img, contours, 3, (0, 255, 0), 3)
cnt = contours[4]
drawContours3 = cv.drawContours(img, [cnt], 0, (0, 255, 0), 3)
plt.figure("轮廓")
plt.subplot(221), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(drawContours1, cmap='gray')
plt.title('drawContours1 Image'), plt.xticks([]), plt.yticks([])
plt.subplot(223), plt.imshow(drawContours2, cmap='gray')
plt.title('drawContours2 Image'), plt.xticks([]), plt.yticks([])
plt.subplot(224), plt.imshow(drawContours3, cmap='gray')
plt.title('drawContours3 Image'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/approxPolyDP.png', 0)
ret, thresh = cv.threshold(img, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
cnt = contours[0]
M = cv.moments(cnt)
print(M)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
print(f"质心:({cx},{cy})")
area = cv.contourArea(cnt)
print(f"area={area}")
perimeter = cv.arcLength(cnt, True)
print(f"perimeter={perimeter}")
temp = np.zeros(img.shape, np.uint8)
img1 = cv.drawContours(temp, contours, -1, (255, 255, 255), 2)
temp = np.zeros(img.shape, np.uint8)
epsilon = 0.1 * cv.arcLength(contours[0], True)
approx = cv.approxPolyDP(contours[0], epsilon, True)
img2 = cv.polylines(temp, [approx], True, (255, 255, 255), 2)
names = ['原图', '轮廓检测结果', '轮廓近似后结果']
images = [img, img1, img2]
plt.figure("轮廓近似")
for i in range(1):
for j in range(3):
plt.subplot(1, 3, i * 3 + j + 1), plt.imshow(images[i * 3 + j], cmap='gray')
plt.title(names[i * 3 + j], fontsize=30), plt.xticks([]), plt.yticks([])
num = i * 3 + j
if num >= len(names) - 1:
break
plt.show()
img = cv.imread('images/hand.png', 0)
img_contour = img.copy()
edges = cv.Canny(img, 120, 255, 0)
contours, hierarchy = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
img_contour = cv.drawContours(img_contour, contours, -1, (0, 255, 0), 2)
hulls = []
for contour in contours:
k = cv.isContourConvex(contour)
print(f"contour的凸出功能:{k}")
hull = cv.convexHull(contour)
hulls.append(hull)
img_convex_hull = cv.drawContours(img, hulls, -1, (0, 255, 0), 2)
plt.figure("凸包检测")
plt.subplot(221), plt.imshow(img, cmap='gray'), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(edges, cmap='gray'), plt.title('edges'), plt.xticks([]), plt.yticks([])
plt.subplot(223), plt.imshow(img_contour, cmap='gray'), plt.title('img_contour'), plt.xticks([]), plt.yticks([])
plt.subplot(224), plt.imshow(img_convex_hull, cmap='gray'), plt.title('img_convex_hull'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/hand.png', 0)
ret, thresh = cv.threshold(img, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
img_contour_rectangle = img.copy()
for contour in contours:
x, y, w, h = cv.boundingRect(contour)
cv.rectangle(img_contour_rectangle, (x, y), (x + w, y + h), (0, 255, 0), 2)
img_contour_rotate = img.copy()
for contour in contours:
rect = cv.minAreaRect(contour)
box = cv.boxPoints(rect)
box = np.intp(box)
cv.drawContours(img_contour_rotate, [box], 0, (0, 0, 255), 2)
plt.figure("边界矩形")
plt.subplot(221), plt.imshow(img), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(img_contour_rectangle), plt.title('img_contour_rectangle'), plt.xticks([]), plt.yticks([])
plt.subplot(223), plt.imshow(img_contour_rotate), plt.title('img_contour_rotate'), plt.xticks([]), plt.yticks([])
plt.show()
img_contour_circle = img.copy()
for contour in contours:
(x, y), radius = cv.minEnclosingCircle(contour)
center = (int(x), int(y))
radius = int(radius)
cv.circle(img_contour_circle, center, radius, (0, 255, 0), 2)
plt.figure("7最小闭合圈")
plt.subplot(221), plt.imshow(img), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(img_contour_circle), plt.title('img_contour_circle'), plt.xticks([]), plt.yticks([])
plt.show()
img_contour_ellipse = img.copy()
contours, hierarchy = cv.findContours(img_contour_ellipse, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
for contour in contours:
if len(contour) >= 5:
ellipse = cv.fitEllipse(contour)
cv.ellipse(img_contour_ellipse, ellipse, (0, 255, 0), 2)
plt.figure("8拟合一个椭圆")
plt.subplot(221), plt.imshow(img), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(img_contour_ellipse), plt.title('img_contour_ellipse'), plt.xticks([]), plt.yticks([])
plt.show()
img_contour_line = img.copy()
rows, cols = img.shape[:2]
for contour in contours:
[vx, vy, x, y] = cv.fitLine(contour, cv.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x * vy / vx) + y)
righty = int(((cols - x) * vy / vx) + y)
cv.line(img_contour_line, (cols - 1, righty), (0, lefty), (0, 255, 0), 2)
plt.figure("9拟合直线")
plt.subplot(221), plt.imshow(img), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(img_contour_line), plt.title('img_contour_line'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/approxPolyDP.png', 0)
ret, thresh = cv.threshold(img, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
cnt = contours[0]
x, y, w, h = cv.boundingRect(cnt)
aspect_ratio = float(w) / h
area = cv.contourArea(cnt)
x, y, w, h = cv.boundingRect(cnt)
rect_area = w * h
extent = float(area) / rect_area
area = cv.contourArea(cnt)
hull = cv.convexHull(cnt)
hull_area = cv.contourArea(hull)
solidity = float(area) / hull_area
area = cv.contourArea(cnt)
equi_diameter = np.sqrt(4 * area / np.pi)
(x, y), (MA, ma), angle = cv.fitEllipse(cnt)
imgray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
mask = np.zeros(imgray.shape, np.uint8)
cv.drawContours(mask, [cnt], 0, 255, -1)
pixelpoints_np = np.transpose(np.nonzero(mask))
pixelpoints_cv = cv.findNonZero(mask)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(imgray, mask=mask)
mean_val = cv.mean(img, mask=mask)
image = cv.imread('images/approxPolyDP.png', 0)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
_, thresholded = cv.threshold(gray, 200, 255, cv.THRESH_BINARY)
contours, _ = cv.findContours(thresholded, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for contour in contours:
hull = cv.convexHull(contour, returnPoints=False)
defects = cv.convexityDefects(contour, hull)
if defects is not None:
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(contour[s][0])
end = tuple(contour[e][0])
far = tuple(contour[f][0])
cv.circle(image, far, 5, [0, 0, 255], -1)
cv.imshow('Image with Convex Hull and Far Points', image)
cv.waitKey(0)
cv.destroyAllWindows()
img = cv.imread('images/star.png')
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(img_gray, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, 2, 1)
cnt = contours[0]
hull = cv.convexHull(cnt, returnPoints=False)
defects = cv.convexityDefects(cnt, hull)
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv.line(img, start, end, [0, 255, 0], 2)
cv.circle(img, far, 5, [0, 0, 255], -1)
cv.imshow('凸性缺陷', img)
cv.waitKey(0)
cv.destroyAllWindows()
dist = cv.pointPolygonTest(cnt, (50, 50),
True)
print(dist)
img1 = cv.imread('images/star.png', 0)
img2 = cv.imread('images/star2.png', 0)
ret, thresh1 = cv.threshold(img1, 127, 255, 0)
ret, thresh2 = cv.threshold(img2, 127, 255, 0)
contours1, hierarchy = cv.findContours(thresh1, 2, 1)
cnt1 = contours1[0]
contours2, hierarchy = cv.findContours(thresh2, 2, 1)
cnt2 = contours2[0]
ret = cv.matchShapes(cnt1, cnt2, 1, 0.0)
print(ret)
img = cv.imread('images/star.png', 0)
hist_cv = cv.calcHist([img], [0], None, [256], [0, 256])
hist_np, bins = np.histogram(img.ravel(), 256, [0, 256])
plt.figure("OpenCV & Numpy中的直方图计算")
plt.subplot(131), plt.imshow(img), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(132), plt.plot(hist_cv), plt.title('OpenCV中的直方图计算hist')
plt.subplot(133), plt.plot(hist_np), plt.title('Numpy中的直方图计算hist')
plt.show()
plt.figure("使用Matplotlib绘制直方图")
plt.hist(img.ravel(), 256, [0, 256]);
plt.show()
imgRGB = cv.imread('images/1.png')
color = ('b', 'g', 'r')
plt.figure("BGR图的直方图计算")
for i, col in enumerate(color):
histr = cv.calcHist([imgRGB], [i], None, [256], [0, 256])
plt.plot(histr, color=col)
plt.xlim([0, 256])
plt.show()
img = cv.imread('images/shudu.png', 0)
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv.bitwise_and(img, img, mask=mask)
hist_full = cv.calcHist([img], [0], None, [256], [0, 256])
hist_mask = cv.calcHist([img], [0], mask, [256], [0, 256])
plt.figure("掩码图像直方图")
plt.subplot(221), plt.imshow(img, 'gray'), plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(mask, 'gray'), plt.title('掩码'), plt.xticks([]), plt.yticks([])
plt.subplot(223), plt.imshow(masked_img, 'gray'), plt.title('掩码后图像'), plt.xticks([]), plt.yticks([])
plt.subplot(224), plt.plot(hist_full, label='原图像直方图'), plt.plot(hist_mask, label='掩码图像直方图'), plt.xlabel(
'Pixel Value'), plt.ylabel('Frequency')
plt.xlim([0, 256])
plt.show()
img = cv.imread('images/star.png', 0)
hist_cv = cv.calcHist([img], [0], None, [256], [0, 256])
plt.figure("直方图均衡")
plt.subplot(131), plt.imshow(img, 'gray'), plt.title('原图')
plt.subplot(132), plt.plot(hist_cv), plt.title('直方图')
hist, bins = np.histogram(img.flatten(), 256, [0, 256])
cdf = hist.cumsum()
cdf_normalized = cdf * float(hist.max()) / cdf.max()
plt.subplot(133), plt.plot(cdf_normalized, color='b'), plt.hist(img.flatten(), 256, [0, 256], color='r'), plt.title(
'直方图均衡')
plt.xlim([0, 256])
plt.legend(('cdf', 'histogram'), loc='upper left')
plt.show()
cdf_m = np.ma.masked_equal(cdf, 0)
cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())
cdf = np.ma.filled(cdf_m, 0).astype('uint8')
img2 = cdf[img]
plt.figure("直方图均衡")
plt.subplot(121), plt.imshow(img, 'gray'), plt.title('原图')
plt.subplot(122), plt.imshow(img2, 'gray'), plt.title('直方图均衡后图像')
plt.show()
img = cv.imread('images/star.png', 0)
equ = cv.equalizeHist(img)
res = np.hstack((img, equ))
plt.figure("OpenCV中的直方图均衡")
plt.subplot(121), plt.imshow(img, 'gray'), plt.title('原图')
plt.subplot(122), plt.imshow(res, 'gray'), plt.title('OpenCV中的直方图均衡')
plt.show()
img = cv.imread('images/star.png', 0)
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
cl1 = clahe.apply(img)
plt.figure("自适应直方图均衡")
plt.subplot(121), plt.imshow(img, 'gray'), plt.title('原图')
plt.subplot(122), plt.imshow(cl1, 'gray'), plt.title('自适应直方图均衡')
plt.show()
img = cv.imread('images/1.png')
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
hist_2d_cv = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
h, s, v = cv.split(hsv)
hist_2d_np, xbins, ybins = np.histogram2d(h.ravel(), s.ravel(), [180, 256], [[0, 180], [0, 256]])
plt.figure("二维直方图")
plt.subplot(121), plt.imshow(hist_2d_cv, interpolation='nearest'), plt.title('opencv二维直方图')
plt.subplot(122), plt.imshow(hist_2d_np, interpolation='nearest'), plt.title('numpy二维直方图')
plt.show()
roi = cv.imread('images/1.png')
hsv = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
target = cv.imread('images/1.png')
hsvt = cv.cvtColor(target, cv.COLOR_BGR2HSV)
roihist = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
cv.normalize(roihist, roihist, 0, 255, cv.NORM_MINMAX)
dst = cv.calcBackProject([hsvt], [0, 1], roihist, [0, 180, 0, 256], 1)
disc = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
cv.filter2D(dst, -1, disc, dst)
ret, thresh = cv.threshold(dst, 50, 255, 0)
thresh = cv.merge((thresh, thresh, thresh))
res = cv.bitwise_and(target, thresh)
res = np.vstack((target, thresh, res))
plt.figure("直方图反投影")
plt.subplot(121), plt.imshow(roi, interpolation='nearest'), plt.title('原图')
plt.subplot(122), plt.imshow(res, interpolation='nearest'), plt.title('直方图反投影')
plt.show()
img = cv.imread('images/1.png', 0)
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20 * np.log(np.abs(fshift))
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(magnitude_spectrum, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
rows, cols = img.shape
crow, ccol = rows // 2, cols // 2
fshift[crow - 30:crow + 31, ccol - 30:ccol + 31] = 0
f_ishift = np.fft.ifftshift(fshift)
img_back = np.fft.ifft2(f_ishift)
img_back = np.real(img_back)
plt.subplot(131), plt.imshow(img, cmap='gray'), plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(132), plt.imshow(img_back, cmap='gray'), plt.title('Image after HPF'), plt.xticks([]), plt.yticks([])
plt.subplot(133), plt.imshow(img_back), plt.title('Result in JET'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/zlh.jpg', 0)
dft = cv.dft(np.float32(img), flags=cv.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20 * np.log(cv.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(magnitude_spectrum, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
rows, cols = img.shape
crow, ccol = int(rows / 2), int(cols / 2)
mask = np.zeros((rows, cols, 2), np.uint8)
mask[crow - 30:crow + 30, ccol - 30:ccol + 30] = 1
fshift = dft_shift * mask
f_ishift = np.fft.ifftshift(fshift)
img_back = cv.idft(f_ishift)
img_back = cv.magnitude(img_back[:, :, 0], img_back[:, :, 1])
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img_back, cmap='gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
mean_filter = np.ones((3, 3))
x = cv.getGaussianKernel(5, 10)
gaussian = x * x.T
scharr = np.array([[-3, 0, 3],
[-10, 0, 10],
[-3, 0, 3]])
sobel_x = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
sobel_y = np.array([[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]])
laplacian = np.array([[0, 1, 0],
[1, -4, 1],
[0, 1, 0]])
filters = [mean_filter, gaussian, laplacian, sobel_x, sobel_y, scharr]
filter_name = ['mean_filter', 'gaussian', 'laplacian', 'sobel_x', 'sobel_y', 'scharr_x']
fft_filters = [np.fft.fft2(x) for x in filters]
fft_shift = [np.fft.fftshift(y) for y in fft_filters]
mag_spectrum = [np.log(np.abs(z) + 1) for z in fft_shift]
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(mag_spectrum[i], cmap='gray')
plt.title(filter_name[i]), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/zlh.jpg', 0)
img2 = img.copy()
template = cv.imread('images/zlh_template.png', 0)
w, h = template.shape[::-1]
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
fig, axs = plt.subplots(4, 2, figsize=(10, 10))
for i, meth in enumerate(methods):
img = img2.copy()
method = eval(meth)
res = cv.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv.rectangle(img, top_left, bottom_right, 255, 2)
axs[i // 2, i % 2].imshow(img, cmap='gray')
axs[i // 2, i % 2].set_title(meth)
axs[i // 2, i % 2].axis('off')
axs[3, 0].imshow(img, cmap='gray')
axs[3, 0].set_title("原图")
axs[3, 0].axis('off')
axs[3, 1].imshow(template, cmap='gray')
axs[3, 1].set_title("模板")
axs[3, 1].axis('off')
plt.show()
img = cv.imread('images/zlh.jpg', cv.COLOR_BGR2RGB)
img_rgb = img.copy()
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('images/zlh_template.png', 0)
w, h = template.shape[::-1]
res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv.imwrite('res.png', img_rgb)
plt.subplot(231), plt.imshow(img, cmap='gray')
plt.title('img'), plt.xticks([]), plt.yticks([])
plt.subplot(232), plt.imshow(img_gray, cmap='gray')
plt.title('img_gray'), plt.xticks([]), plt.yticks([])
plt.subplot(233), plt.imshow(template, cmap='gray')
plt.title('template'), plt.xticks([]), plt.yticks([])
plt.subplot(234), plt.imshow(res, cmap='gray')
plt.title('res'), plt.xticks([]), plt.yticks([])
plt.subplot(235), plt.imshow(img_rgb, cmap='gray')
plt.title('img_rgb'), plt.xticks([]), plt.yticks([])
plt.show()
image = cv.imread('images/shudu.png')
img = image.copy()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 30, 90, apertureSize=3)
lines = cv.HoughLines(edges, 1, np.pi / 180, 100)
for line in lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * (a))
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * (a))
cv.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
plt.figure("霍夫线变换")
plt.subplot(221), plt.imshow(image, cmap='gray'), plt.title('原图'), plt.xticks([]), plt.yticks([])
plt.subplot(222), plt.imshow(edges, cmap='gray'), plt.title('Canny检测边缘'), plt.xticks([]), plt.yticks([])
plt.subplot(223), plt.imshow(img, cmap='gray'), plt.title('Opencv霍夫线变换'), plt.xticks([]), plt.yticks([])
img = image.copy()
lines = cv.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10)
for line in lines:
x1, y1, x2, y2 = line[0]
cv.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
plt.subplot(224), plt.imshow(img, cmap='gray'), plt.title('概率霍夫变换'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/opencv-logo.png', 0)
img = cv.medianBlur(img, 5)
cimg = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 20,
param1=50, param2=30, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
cv.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
cv.imshow('detected circles', cimg)
cv.waitKey(0)
cv.destroyAllWindows()
image = cv.imread('images/coins.png', cv.IMREAD_COLOR)
img = image.copy()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
kernel = np.ones((3, 3), np.uint8)
opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv.dilate(opening, kernel, iterations=3)
dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5)
ret, sure_fg = cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
sure_fg = np.uint8(sure_fg)
unknown = cv.subtract(sure_bg, sure_fg)
ret, markers = cv.connectedComponents(sure_fg)
markers = markers + 1
markers[unknown == 255] = 0
markers = cv.watershed(img, markers)
img[markers == -1] = [255, 0, 0]
plt.figure("图像分割与Watershed算法")
plt.subplot(331), plt.imshow(cv.cvtColor(image, cv.COLOR_BGR2RGB)), plt.title('image原图'), plt.xticks([]), plt.yticks(
[])
plt.subplot(332), plt.imshow(thresh), plt.title('thresh使用Otsu的二值化'), plt.xticks([]), plt.yticks([])
plt.subplot(333), plt.imshow(opening), plt.title('opening开运算'), plt.xticks([]), plt.yticks([])
plt.subplot(334), plt.imshow(sure_bg), plt.title('sure_bg背景区域'), plt.xticks([]), plt.yticks([])
plt.subplot(335), plt.imshow(dist_transform), plt.title('dist_transform'), plt.xticks([]), plt.yticks([])
plt.subplot(336), plt.imshow(sure_fg), plt.title('sure_fg前景区域'), plt.xticks([]), plt.yticks([])
plt.subplot(337), plt.imshow(unknown), plt.title('unknown未知区域'), plt.xticks([]), plt.yticks([])
plt.subplot(338), plt.imshow(markers), plt.title('markers类别标记'), plt.xticks([]), plt.yticks([])
plt.subplot(339), plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB)), plt.title('img结果'), plt.xticks([]), plt.yticks([])
plt.show()
img = cv.imread('images/coins.png')
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (50, 50, 450, 290)
cv.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
plt.imshow(img), plt.colorbar(), plt.show()
newmask = cv.imread('newmask.png', 0)
mask[newmask == 0] = 0
mask[newmask == 255] = 1
mask, bgdModel, fgdModel = cv.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv.GC_INIT_WITH_MASK)
mask = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask[:, :, np.newaxis]
plt.imshow(img), plt.colorbar(), plt.show()
6.特征检测与描述