[英]how to binaries the image, assign the zeros and one into 2D image by a threshold point using python and convert it to RGB?
我已经在MATLAB中编写了以下代码,并希望将其转换为python代码。 我们如何在python中找到MatLab指令:
MatLab代码:
path = 'C:\Users\hp\Desktop\output\result_0.png';
img = imread(path);
size(img)
img = rgb2gray(img);
size(img)
m = mean(img(:));
img = img>m;
RGB = cat(3, img, img, img);
size(RGB)
Python程式码:
path = r"C:\\Users\\hp\\Desktop\\output\\result_0.png"
img = cv2.imread(path)
print(img.shape)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
result = gray.flatten()
m = statistics.mean(result)
print(m)
gray = gray>m
img = gray.astype(int)
print(img)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
如何更正python代码,使其像MatLab代码一样工作?
运行python代码后出现错误:
Traceback (most recent call last):
File "C:/pytorch-GaitGAN-master/src/test2.py", line 24, in <module>
cv2.imshow('image',img)
cv2.error: OpenCV(4.0.0) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:261: error: (-2:Unspecified error) in function '__cdecl cv::CvtHelper<struct cv::Set<1,-1,-1>,struct cv::Set<3,4,-1>,struct cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'
> Unsupported depth of input image:
> 'VDepth::contains(depth)'
> where
> 'depth' is 4 (CV_32S)
下面的代码,我是必需的:
import cv2
import numpy as np
path = r"C:\\Users\\hp\\Desktop\\output\\result_0.png"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray[gray<np.mean(gray)] = 0.
gray[gray>=np.mean(gray)] = 255.
print(gray.shape)
img = np.stack((gray,)*3, axis=-1)
print(img.shape)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
根据您的Matlab代码,我认为您想基于平均值m
对图像进行阈值处理。 您可以使用cv2.threshold
来执行此操作。
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
result = gray.flatten()
m = statistics.mean(result)
gray_thres = cv2.threshold(gray,m,255,cv2.THRESH_BINARY)
您可能需要将值255更改为图像中的最大值。 更多信息在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.