如何保存此代码中的图像结果?

时间:2019-02-09 15:57:49

标签: python-3.x opencv

我正在尝试编写代码来识别长尾小鹦鹉的眼睛。到目前为止,我设法使用了识别圆弧边缘并在一定阈值下获得了不错结果的代码。但是我无法保存结果图像。

我尝试使用imwrite('result.png', clone)将结果保存在代码末尾,但是运行它时,我会得到TypeError: Expected cv::UMat for argument 'img'.
我也需要给克隆图像上色,但是我不知道从哪里开始。

import cv2
import numpy as np
import imutils

def nothing(x): 
pass

# Load an image 
img = cv2.imread('sample.png')

# Resize The image
if img.shape[1] > 600:
img = imutils.resize(img, width=600)

# Create a window
cv2.namedWindow('Treshed')

# create trackbars for treshold change
cv2.createTrackbar('Treshold','Treshed',0,255,nothing)


while(1):

# Clone original image to not overlap drawings
clone = img.copy()

# Convert to gray
gray = cv2.cvtColor(clone, cv2.COLOR_BGR2GRAY)

# get current positions of four trackbars
r = cv2.getTrackbarPos('Treshold','Treshed')

# Thresholding the gray image
ret,gray_threshed = cv2.threshold(gray,r,255,cv2.THRESH_BINARY)

# Blur an image
bilateral_filtered_image = cv2.bilateralFilter(gray_threshed, 5, 175, 175)

# Detect edges
edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)

# Find contours
contours, _= cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    # approximte for circles
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) > 8) & (area > 30) ):
        contour_list.append(contour)

# Draw contours on the original image
cv2.drawContours(clone, contour_list,  -1, (255,0,0), 2)

# there is an outer boundary and inner boundary for each eadge, so contours double
print('Number of found circles: {}'.format(int(len(contour_list)/2)))

#Displaying the results     
cv2.imshow('Objects Detected', clone)
cv2.imshow("Treshed", gray_threshed)

# ESC to break
k = cv2.waitKey(1) & 0xFF
if k == 27:
    break

# close all open windows
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

我刚刚尝试了这种修改,它可以完美地工作。

# ESC to break
k = cv2.waitKey(1) & 0xFF
if k == 27:
    cv2.imwrite('result.png', clone)
    break

sample.jpg result.png

对于何时何地调用imwrite可能存在误解,或者您的python / opencv版本有些混乱。我使用python 3.6.8和opencv-python 4.0.0.21在pycharm中运行了