我已经从互联网上复制了 c++ 中的 opencv 代码来记录桌面”
#include <iostream>
#include <opencv2/opencv.hpp>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <cstdint>
#include <cstring>
#include <vector>
using namespace std;
using namespace cv;
void ImageFromDisplay(std::vector<uint8_t>& Pixels, int& Width, int& Height, int& BitsPerPixel)
{
Display* display = XOpenDisplay(nullptr);
Window root = DefaultRootWindow(display);
XWindowAttributes attributes = {0};
XGetWindowAttributes(display, root, &attributes);
Width = attributes.width;
Height = attributes.height;
XImage* img = XGetImage(display, root, 0, 0 , Width, Height, AllPlanes, ZPixmap);
BitsPerPixel = img->bits_per_pixel;
Pixels.resize(Width * Height * 4);
memcpy(&Pixels[0], img->data, Pixels.size());
XDestroyImage(img);
XCloseDisplay(display);
}
int main()
{
int Width = 0;
int Height = 0;
int Bpp = 0;
std::vector<std::uint8_t> Pixels;
while(true)
{
namedWindow("Display window",WINDOW_NORMAL);
ImageFromDisplay(Pixels, Width, Height, Bpp);
if (Width && Height)
{
Mat img = Mat(Height, Width, Bpp > 24 ? CV_8UC4 : CV_8UC3, &Pixels[0]); //Mat(Size(Height, Width), Bpp > 24 ? CV_8UC4 : CV_8UC3, &Pixels[0]);
namedWindow("WindowTitle", WINDOW_AUTOSIZE);
imshow("Display window", img);
waitKey(1);
}
}
return 0;
}
一切正常。 imshow 窗口显示的正是我的桌面。
但是,我的老板说每个程序都应该在 docker 中。
我写了一个dockerfile并将程序放入其中
FROM x11docker/xfce
ENV TZ=Asia/Taibei
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN apt-get update && apt-get install -y \
build-essential \
cmake \
git \
libatlas-base-dev \
libgtk2.0-dev \
libjpeg-dev \
libpng-dev \
libtiff-dev \
libvtk6-dev \
pkg-config \
qt5-default \
wget \
zlib1g-dev
RUN apt-get install cmake-qt-gui
RUN git clone https://github.com/opencv/opencv.git && \
cd ./opencv && \
mkdir build && \
cd build && \
cmake \
-D BUILD_SHARED_LIBS=ON \
-D WITH_QT=ON \
-D WITH_OPENGL=ON \
-D FORCE_VTK=ON \
-D WITH_TBB=ON \
-D WITH_GDAL=ON \
-D WITH_V4L=ON \
-D WITH_XINE=ON \
-D BUILD_EXAMPLES=OFF \
-D ENABLE_PRECOMPILED_HEADERS=OFF \
-D BUILD_DOCS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D BUILD_TESTS=OFF \
-D BUILD_opencv_apps=OFF \
-D CMAKE_INSTALL_PREFIX=/home/gino/opencv_install \
.. && \
make -j8 && \
make install && \
ldconfig
ADD ./ /home/gino/cvtest/
WORKDIR /home/gino/cvtest/
RUN make
ENV HOME /home/developer
为了显示 GUI,我使用 x11docker 运行图像。但是docker中的程序只能获取镜像的桌面。
如何通过docker中的程序记录主机的桌面?
最佳答案
在另一个人的 blog 上找到答案
首先,使用命令使其他用户可以访问x11:
xhost +
第二,运行镜像(镜像名称为“catchdesktop”)sudo docker run --net=host --env="DISPLAY" --volume="$HOME/.Xauthority:/root/.Xauthority:rw" catchdesktop
现在我可以看到我的主机桌面出现在 docker 的 opencv 程序中。关于c++ - 如何从docker中的程序记录主机桌面(ubuntu中的c++ opencv)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63497849/