簡體   English   中英

如何對圖像進行二進制處理,使用python通過閾值點將零和一分配為2D圖像並將其轉換為RGB?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM