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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何保存此代码的图像结果?相关的知识,希望对你有一定的参考价值。

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

我已经尝试使用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()
答案

我只是尝试了这个修改,它完美无缺。

# 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中运行它

以上是关于如何保存此代码的图像结果?的主要内容,如果未能解决你的问题,请参考以下文章

为啥此代码片段返回意外结果?

我在哪里更改此 Python 代码片段以将临时文件保存在 tmp 文件夹中?

如何在c#中扫描图像并以正常大小保存

如何在不将图像保存在本地的情况下将捕获的图像(Surface View)传递给另一个片段?

Adobe AIR的 - 硬盘上保存图像

如何从Android片段中的相机获取图像