python-opencv如何遍历图片

使用背景

  • 一个朋友,需要查看鸡蛋是否有裂纹,如下图所示:
  • 之后通过python-opencv处理成为了如下结果:
  • 如上图所示,通过canny轮廓提取得到了左图所示轮廓,通过阈值分割得到右图所示裂纹,此时需要把裂纹移植到轮廓图片中,最终结果如下图所示:
  • 我用的是遍历裂纹图,将黑色的裂纹移植到轮廓图中。以下代码实现了裂纹图片的遍历。

代码实现

import cv2
import numpy as np

egg=cv2.imread(r'C:\Users\ZFG\PycharmProjects\Lenet_test\egg.jpg',0)
egg_canny=cv2.Canny(egg,32,64)
ret,egg_thresh=cv2.threshold(egg,100,255,cv2.THRESH_BINARY_INV)

thre,bw=cv2.threshold(egg,30,255,cv2.THRESH_BINARY)
kernel=np.ones((3,3),np.uint8)
opening=cv2.morphologyEx(bw,cv2.MORPH_OPEN,kernel)
#遍历图片每一个像素点,由于是灰度图,所以不需要遍历通道,只需要遍历像素值的每一个位置
height = opening.shape[0]
weight = opening.shape[1]
for i in range(height):
    for j in range(weight):
        if egg_thresh[i,j]==0:
            opening[i,j]=egg_thresh[i,j]
cv2.imshow('egg_thresh',egg_thresh)
cv2.imshow('opening',opening)
print(egg_thresh)
cv2.waitKey(0)

猜你喜欢

转载自blog.csdn.net/weixin_50233398/article/details/120017091