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

问题描述 投票:0回答:1

我正在尝试编写一个识别长尾小鹦鹉眼睛的代码。到目前为止,我已设法使用识别圆边的代码,并在某个阈值处获得了很好的结果。但我无法保存结果图像。

我已经尝试使用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()
python-3.x opencv
1个回答
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中运行它

© www.soinside.com 2019 - 2024. All rights reserved.