如何在移动设备上突出显示异常标记

时间:2020-02-08 17:34:42

标签: python opencv computer-vision

我正在处理示例任务,需要在任何移动设备上突出显示不寻常的标记。我正在尝试使用opencv python。但是,对于异常标记,我没有得到真正的帮助。

输入图片如下:

enter image description here

预期输出图像如下: enter image description here

我正在尝试类似下面的操作,但是没有用。

import cv2
from matplotlib import pyplot as plt

blurValue = 15
img_path = "input.jpg"

# reading the image 
image = cv2.imread(img_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (blurValue, blurValue), 0)
edged = cv2.Canny(image, 100, 255)

#applying closing function 
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)
lower = np.array([4, 20, 93])
upper = np.array([83, 79, 166])

# hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# blur = cv2.GaussianBlur(hsv, (blurValue, blurValue), 0)

mask = cv2.inRange(closed, lower, upper)
result_1 = cv2.bitwise_and(frame, frame, mask = mask)
cnts = cv2.findContours(result_1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
plt.imshow(image)
plt.title("image")
plt.show()

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:3)

我的建议是对区域(以及可能的其他特征)使用自适应阈值和过滤。这是我使用Python OpenCV的代码和结果。

输入:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread("iphone.jpg")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# apply gaussian blur
blur = cv2.GaussianBlur(gray, (29,29), 0)

# do adaptive threshold on gray image
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 51, 3)

# apply morphology open then close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 17))
open = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
close = cv2.morphologyEx(open, cv2.MORPH_CLOSE, kernel)

# Get contours
cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
result = img.copy()
for c in cnts:
    area = cv2.contourArea(c)
    if area < 10000 and area > 5000:
        cv2.drawContours(result, [c], -1, (0, 255, 0), 2)


# write results to disk
cv2.imwrite("iphone_thresh.jpg", thresh)
cv2.imwrite("iphone_close.jpg", close)
cv2.imwrite("iphone_markings.jpg", result)

# display it
cv2.imshow("IMAGE", img)
cv2.imshow("THRESHOLD", thresh)
cv2.imshow("CLOSED", close)
cv2.imshow("RESULT", result)
cv2.waitKey(0)


阈值图像:

enter image description here

形态处理过的图像:

enter image description here

最终结果:

enter image description here

我还建议您将图像与已知的干净iPhone图像对齐,并创建照相机和徽标等遮罩的标记,以便可以过滤结果以排除那些结果(甚至可能排除图像的边框)。相机轮廓)。