Search code examples
python-3.xopencvadb

How to show ADB screenshot directly in python?


I want to display screenshot from adb screencap directly in python without generate a file, is there any way to do this?

I have tried opencv, here is my code:

command = r"adb shell screencap -p"
proc = subprocess.Popen(shlex.split(command),stdout=subprocess.PIPE)
out = proc.stdout.read(30000000)
img = cv2.imdecode(out,cv2.IMREAD_COLOR)
if img is not None:
    cv2.imshow("",img)
    cv2.waitKey(0)
    cv2.destroyWindow("")

but I got this error on "imdecode" line:

TypeError: buf is not a numpy array, neither a scalar

I am using python3.6 and OpenCV3.4, on Windows 7. ADB v1.0.36, Android version is 8.0

Does anyone know how to do this? Thanks.


Solution

  • Thanks to GPPK, now it's working:

    pipe = subprocess.Popen("adb shell screencap -p",
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE, shell=True)
    image_bytes = pipe.stdout.read().replace(b'\r\n', b'\n')
    image = cv2.imdecode(np.fromstring(image_bytes, np.uint8), cv2.IMREAD_COLOR)
    cv2.imshow("", image)
    cv2.waitKey(0)
    cv2.destroyWindow("")