首页 > 解决方案 > “有什么方法可以通过特定位置(例如opencvforunity中的(x,y))在图像中访问像素”

问题描述

我正在尝试按位置访问图像像素,我一直使用字节数组进行访问,但它没有像 python image[x][y] 那样给出 x,y 的正确位置。有没有更好的方法来访问像素?

我在unity,visual studio中使用过opencv插件,无法访问它们

public texture2D image;

Mat imageMat = new Mat(image.height, image.width, CvType.CV_8UC4);
Utils.texture2DToMat(image, imageMat); // actually converts texture2d to matrix

byte[] imageData = new byte[(int)(imageMat.total() * imageMat.channels())]; // pixel data of image
imageMat.get(0, 0, imageData);// gets pixel data

pixel=imageData[(y * imageMat.cols() + x) * imageMat.channels() + r]

y 和 x 是代码中的像素值,r 是通道,但我无法使用该代码访问 x 和 y 的特定值

标签: c#opencvunity3d

解决方案


没有通常的方法可以做到这一点,因为操作真的很慢。但是一些技巧是你可以从“相机”类中制作屏幕纹理。

制作纹理后,您可以使用 texture.GetPixel(x,y)

public class Example : MonoBehaviour
{
    // Take a "screenshot" of a camera's Render Texture.
    Texture2D RTImage(Camera camera)
    {
        // The Render Texture in RenderTexture.active is the one
        // that will be read by ReadPixels.
        var currentRT = RenderTexture.active;
        RenderTexture.active = camera.targetTexture;

        // Render the camera's view.
        camera.Render();

        // Make a new texture and read the active Render Texture into it.
        Texture2D image = new Texture2D(camera.targetTexture.width, camera.targetTexture.height);
        image.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0);
        image.Apply();

        // Replace the original active Render Texture.
        RenderTexture.active = currentRT;
        return image;
    }
}

推荐阅读