python - OpenCV 检测水果上的划痕
问题描述
对于我正在做的 Python 小实验,我想在水果上找到小划痕。划痕非常小,人眼难以察觉。
我正在使用高分辨率相机进行该实验。
这是我要检测的缺陷:
原图:
这是我用很少几行代码得到的结果:
所以我找到了我的水果的轮廓。我怎样才能继续寻找划痕?RGB 值与水果的其他部分相似。那么如何区分划痕和水果的一部分呢?
我的代码:
# Imports
import numpy as np
import cv2
import time
# Read Image & Convert
img = cv2.imread('IMG_0441.jpg')
result = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Filtering
lower = np.array([1,60,50])
upper = np.array([255,255,255])
result = cv2.inRange(result, lower, upper)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(9,9))
result = cv2.dilate(result,kernel)
# Contours
im2, contours, hierarchy = cv2.findContours(result.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
result = cv2.cvtColor(result, cv2.COLOR_GRAY2BGR)
if len(contours) != 0:
for (i, c) in enumerate(contours):
area = cv2.contourArea(c)
if area > 100000:
print(area)
cv2.drawContours(img, c, -1, (255,255,0), 12)
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),12)
# Stack results
result = np.vstack((result, img))
resultOrig = result.copy()
# Save image to file before resizing
cv2.imwrite(str(time.time())+'_0_result.jpg',resultOrig)
# Resize
max_dimension = float(max(result.shape))
scale = 900/max_dimension
result = cv2.resize(result, None, fx=scale, fy=scale)
# Show results
cv2.imshow('res',result)
cv2.waitKey(0)
cv2.destroyAllWindows()
解决方案
推荐阅读
- regex - 如何设置正则表达式的限制?(最小和最大长度)
- c# - 加入 LINQ 查询语法:将右侧移到左侧
- graphics - 给定目标点和相机向前,camera.lookAt 函数可以从角度和旋转轴计算吗?
- assembly - DCX 和进位标志
- stm32 - 接收数据时如何自动调用 UART_Receive_IT()?
- ansible - 有没有办法覆盖定义为 ansible Galaxy 角色的模板?
- sql - 如何为同一个项目添加相同的数字?
- php - PHP $_GET 值从 url 到数组(自定义函数)
- debugging - 可以在 RFC 用户下调试吗?
- c# - 在 sql 中插入新行不接受文本