pencv返回镜像 python_2020-11-08Python——基于opencv的图像处理

本文介绍了如何使用OpenCV在Python中配置环境,进行图像的读取、显示、颜色空间转换。重点讲解了颜色识别,通过设置RGB色域,使用inRange函数和bitwise_and()函数进行图像操作。此外,还讨论了图形轮廓检测,通过findContours、minEnclosingCircle等函数识别不同形状的数量。
摘要由CSDN通过智能技术生成

一.opencv的环境的配置

在终端之中使用pip install opencv来实现相应的opencv的包的下载

亦可以使用国内的镜像的网站来进行相应的下载pip install opencv -i 国内的镜像网站的网址

二.基本操作:

1.读取写入图像:

# 载入图像

im = cv2.imread('./0.png')

2.打印图像的尺寸

# 打印图像尺寸

h,w = im.shape[:2]

print(h,w)

3.保存png格式的图像为jpg格式的图像

# 保存PNG格式图像为JPEG格式

cv2.imwrite('./0.jpg',im)

4.颜色空间的转换

在OpenCV中,图像不是用常规的RGB颜色通道来存储的,他们用的顺序是BGR顺序。当读取一幅图像后,默认的是BGR,不过有很多转换方式可以利用。颜色空间转换函数可以用cvtColor()完成。

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import cv2

# 载入图像

im = cv2.imread('./2.png')

print(im.shape)

# create a grayscale version

gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print(gray.shape)

5.图像的显示

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import cv2

# from matplotlib import pyplot as plt

from pylab import *

# 添加中文字体支持

from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc",size = 14)

# 载入图像

im = cv2.imread('Middlebury_01_clean_color.png')

# 颜色空间转换

gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

# 显示原始图像

fig = plt.figure()

subplot(121)

plt.gray()

imshow(im)

title(u'彩色图', fontproperties= font)

axis('off')

# 显示灰度化图像

plt.subplot(122)

plt.gray()

imshow(gray)

title(u'灰度图', fontproperties= font)

axis('off')

show()

三.其中的一些简单的功能:

使用opencv进行颜色和简单的图像的识别:

1.对于颜色的识别我们使用了RGB设置对应颜色的色域来进行识别:

lower_hsv = np.array([156, 128, 46]) # 提取颜色的低值

high_hsv = np.array([180, 255, 255]) # 提取颜色的高值

2.其中我们使用inrange函数来进行相应的图片的操作:

就是将我们的在RGB色域之中的图片的像素设置为白色,其余的地方设置为相应的黑色,再在其基础上面进行相应的图片的操作

lower_hsv = np.array([156, 128, 46]) # 提取颜色的低值

high_hsv = np.array([180, 255, 255]) # 提取颜色的高值

mask = cv2.inRange(hsv, lowerb=lower_hsv, upperb=high_hsv)

#cv2.imshow('red',mask)

accd6377a3c6

2.png

3.使用“与”操作函数cv2.bitwise_and()对图像掩膜(遮挡):

BlueThings = cv2.bitwise_and(image, image, mask=th1)

accd6377a3c6

1.png

4.对于其中的图形的判断

使用了对于相应的图形的轮廓之中的顶点的个数的判断:

1.使用cv2.findContours函数的作用是寻找轮廓。三个输入参数:输入图像(二值图像,黑色作为背景,白色作为目标),轮廓检索方式,轮廓近似方法。 ,其中就是图片之中每一个图形的轮廓,返回三个值:img(图像)、countours(轮廓)、hierarchy(层次结构)。

edged = cv2.Canny(th1, 60, 150)#边缘的检测,返回的是一个二值图

cnts = cv2.findContours(edged, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

2.使用 imutils.grab_contours函数一般和cv2.findContours函数连用,来返回cnts中的countors(轮廓),

cnts = imutils.grab_contours(cnts)

3.通过cv2.minEnclosingCircle、 cv2.arcLength、 cv2.approxPolyDP函数来获取相应图形的顶点的个数,其中cv2.minEnclosingCircle来获取相应的包含图形轮廓的最小的圆轮廓; cv2.arcLength来获取相应的图形轮廓的长度,cv2.approxPolyDP设置相应的阈值来获取相应的顶点的集合,其中的第二个参数是一个固定的值:0.02 * 相应的轮廓的长度

for c in cnts:

# if the contour area is small, then the area is likely noise, so

# we should ignore the contour

(x,y),radius = cv2.minEnclosingCircle(c)

center = (int(x)+int(radius),int(y))

peri = cv2.arcLength(c, True)

approx = cv2.approxPolyDP(c, 0.02 * peri, True)

# 如果当前的轮廓含有3个顶点,则其为三角形

实例:

import imutils

import cv2

import numpy as np

font=cv2.FONT_HERSHEY_COMPLEX

imgpath=r'image.jpg'

image = cv2.imread(imgpath)

b = image.shape

cy = np.zeros(list(b[:2]))

#cv2.imshow('image',image)

hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # 色彩空间转换为hsv,便于分离

lower_hsv = np.array([156, 128, 46]) # 提取颜色的低值

high_hsv = np.array([180, 255, 255]) # 提取颜色的高值

mask = cv2.inRange(hsv, lowerb=lower_hsv, upperb=high_hsv)

cv2.imshow('red',mask)

blurred = cv2.GaussianBlur(mask, (9, 9), 0)

ret,th1=cv2.threshold(blurred,110,255,cv2.THRESH_BINARY)

BlueThings = cv2.bitwise_and(image, image, mask=th1)

#cv2.imshow('BlueThings',BlueThings)

result = BlueThings

# write result to disk

cv2.imwrite("image1.jpg", result)

result1 = cv2.imread("image.jpg")

h, w, c = result1.shape

hsv1 = cv2.cvtColor(result1,cv2.COLOR_BGR2HSV)

lower_red= np.array([0,0,0])

upper_red = np.array([180,255,46])

mask1 = cv2.inRange(hsv1, lower_red, upper_red)

erode=cv2.erode(mask1,None,iterations=1)

#cv2.imshow('erode',erode)

dilate=cv2.dilate(erode,None,iterations=1)

#cv2.imshow('dilate',dilate)

for i in range(h):

for j in range(w):

if dilate[i,j]==255: #像素点255表示白色

result1[i,j]=(255,255,255) # 此处替换颜色,为BGR通道,不是RGB通道

#cv2.imshow('edged',result1)

edged = cv2.Canny(th1, 60, 150)

cnts = cv2.findContours(edged, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

cnts = imutils.grab_contours(cnts)

total = 0

Circleshape,Threeshape,Foreshape = 0,0,0

# loop over the contours one by one

for c in cnts:

# if the contour area is small, then the area is likely noise, so

# we should ignore the contour

(x,y),radius = cv2.minEnclosingCircle(c)

center = (int(x)+int(radius),int(y))

peri = cv2.arcLength(c, True)

approx = cv2.approxPolyDP(c, 0.02 * peri, True)

# 如果当前的轮廓含有3个顶点,则其为三角形

if len(approx) == 3:

Threeshape = Threeshape + 1

result=cv2.putText(result1,'Three'+str(Threeshape),center,font,0.5,(0,0,0))

# 如果当前的轮廓含有4个顶点,则其可能是矩形或者正方形

elif len(approx) == 4:

Foreshape = Foreshape + 1

result=cv2.putText(result1,'Fore'+str(Foreshape),center,font,0.5,(0,0,0))

else:

Circleshape =Circleshape + 1

result=cv2.putText(result1,'Circle'+str(Circleshape),center,font,0.5,(0,0,0))

# otherwise, draw the contour on the image and increment the total

# number of shapes found

#cv2.drawContours(image, [c], -1, (204, 0, 255), 2)

total += 1

# show the output image and the final shape count

info="[INFO] found {} Red shapes".format(total)

a1="[INFO] found {} Circleshape".format(Circleshape)

a2="[INFO] found {} Threeshape".format(Threeshape)

a3="[INFO] found {} Foreshape".format(Foreshape)

result=cv2.putText(result1,info,(700,40),font,0.5,(0,255,10))

result=cv2.putText(result1,a1,(700,60),font,0.5,(0,255,10))

result=cv2.putText(result1,a2,(700,80),font,0.5,(0,255,10))

result=cv2.putText(result1,a3,(700,100),font,0.5,(0,255,10))

print("[INFO] found {} Red shapes".format(total))

print("[INFO] found {} Circleshape".format(Circleshape))

print("[INFO] found {} Threeshape".format(Threeshape))

print("[INFO] found {} Foreshape".format(Foreshape))

cv2.imshow("Image1", result1)

cv2.waitKey(0)

cv2.destroyAllWindows()

实现结果:

accd6377a3c6

图片2.png

accd6377a3c6

blue.png

accd6377a3c6

green.png

accd6377a3c6

red.png

accd6377a3c6

图片1.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值