[关闭]
@gzm1997 2017-12-05T06:53:53.000000Z 字数 2019 阅读 754

数字媒体技术作业2

树媒技术基础作业


郭柱明 15331094


实验环境

opencv版本为3.3.1,PIL版本为4.1.1
image_1c0imec311da6sjb1p2617vr1p8k1g.png-4.7kB


实验步骤

import相关模块opencv

  1. import cv2
  2. from PIL import Image

读取图片为rgb数组,用作第一次轮廓检测

  1. im = cv2.imread('patch.jpg')

转为灰度矩阵,用以二值化

  1. imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

进行二值化

  1. ret, thresh = cv2.threshold(imgray, 169, 255, 0)

使用进行了二值化的矩阵进行轮廓检测

  1. im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

在原图中画出轮廓,画迹宽度为3

  1. cv2.drawContours(im, contours, -1, (0,255,0), 3)

对画出了轮廓了的图像矩阵进行第二次轮廓检测(这样检测出来的轮廓才是连续的)

转为灰度矩阵

  1. imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

第二次二值化

  1. ret, thresh = cv2.threshold(imgray, 169, 255, 0)

第二次轮廓检测,此时获得的轮廓才是连续的,第一次获得的是断断续续的

  1. im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

去掉第一个轮廓,那时整张A4纸的边框

  1. contours = contours[1:]

新打开一次原图用作圈出轮廓

  1. img = cv2.imread("patch.jpg")

对每个轮廓

  1. index = 0
  2. for c in contours:
  3. #获取每个轮廓被包围的矩形的横纵坐标和宽高
  4. x, y, w, h = cv2.boundingRect(c)
  5. #画出包围每个轮廓的矩形
  6. cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
  7. #展示每个被圈住的轮廓
  8. Image.fromarray(img[y:y+h,x:x+w,:]).save(str(index) + ".png")
  9. index += 1

展示画出包围轮廓的矩形的图像

  1. cv2.imshow("Contours", img)
  2. cv2.waitKey(0)
  3. cv2.destroyAllWindows()

运行结果

0.png-4.6kB
1.png-7.7kB
2.png-5.3kB
3.png-2.1kB
4.png-1.2kB
5.png-1.9kB
6.png-5.6kB

image_1c0ilkrmf12goieo1s6d1o6j1lamm.png-217.7kB

完整代码

  1. import cv2
  2. from PIL import Image
  3. #读取图片为rgb数组,用作第一次轮廓检测
  4. im = cv2.imread('patch.jpg')
  5. #转为灰度矩阵,用以二值化
  6. imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
  7. #进行二值化
  8. ret, thresh = cv2.threshold(imgray, 169, 255, 0)
  9. #使用进行了二值化的矩阵进行轮廓检测
  10. im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  11. #在原图中画出轮廓,画迹宽度为3
  12. cv2.drawContours(im, contours, -1, (0,255,0), 3)
  13. #对画出了轮廓了的图像矩阵进行第二次轮廓检测(这样检测出来的轮廓才是连续的)
  14. #转为灰度矩阵
  15. imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
  16. #第二次二值化
  17. ret, thresh = cv2.threshold(imgray, 169, 255, 0)
  18. #第二次轮廓检测,此时获得的轮廓才是连续的,第一次获得的是断断续续的
  19. im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  20. #去掉第一个轮廓,那时整张A4纸的边框
  21. contours = contours[1:]
  22. #新打开一次原图用作圈出轮廓
  23. img = cv2.imread("patch.jpg")
  24. #对每个轮廓
  25. index = 0
  26. for c in contours:
  27. #获取每个轮廓被包围的矩形的横纵坐标和宽高
  28. x, y, w, h = cv2.boundingRect(c)
  29. #画出包围每个轮廓的矩形
  30. cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
  31. #展示每个被圈住的轮廓
  32. Image.fromarray(img[y:y+h,x:x+w,:]).save(str(index) + ".png")
  33. index += 1
  34. #展示画出包围轮廓的矩形的图像
  35. cv2.imshow("Contours", img)
  36. # 等待键盘输入
  37. cv2.waitKey(0)
  38. #关闭展示窗口
  39. cv2.destroyAllWindows()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注