Convert a kivy texture to opencv image

心已入冬 提交于 2021-02-11 17:09:51

问题


I am trying to convert my kivy texture to an image format so that i can process it using opencv (cv2). I tried reading the texture using read() and using cv2.imread() but neither worked. I also looked into converting the ubyte texture into a string but got nowhere.

kivy camera texture -> format that i can process using cv2

something like

MyVariable = someid.texture
#do something to format of MyVariable so that it is an 'image'
Newvar = MyVariable.read()
#cv2 processing...

EDIT:

Ok so i got the data from the texture using texture.pixel in an RGB array format. I then used

newvalue = np.frombuffer(camera.texture.pixels, np.uint8) 

to get the data into a numpy string. From there it was pretty easy to re display it on an image widget using:

finalstage = newvalue.tostring()
texture1 = Texture.create(size=variables.size, colorfmt='rgba')
texture1.blit_buffer(finalstage, colorfmt='rgba', bufferfmt='ubyte')
image.texture = texture1

my issue is that now i want to use Opencv to draw rectangles on the faces and then update the image texture. I have working code to draw rectangles, however i first need to convert the RGB data to grey using

gray = cv2.cvtColor(newvalue, cv2.COLOR_RGBA2GRAY)

Doing this returns my new error:

11-08 17:22:51.451 25259 25582 E cv::error(): OpenCV(4.0.1) Error: Unspecified error (> Invalid number of channels in input image:
11-08 17:22:51.451 25259 25582 E cv::error(): >     'VScn::contains(scn)'
11-08 17:22:51.451 25259 25582 E cv::error(): > where
11-08 17:22:51.451 25259 25582 E cv::error(): >     'scn' is 1
11-08 17:22:51.451 25259 25582 E cv::error(): ) in cv::CvtHelper<cv::Set<3, 4, -1>, cv::Set<1, -1, -1>, cv::Set<0, 2, 5>, cv::SizePolicy::NONE>::CvtHelper(cv::InputArray, cv::OutputArray, int) [VScn = cv::Set<3, 4, -1>, VDcn = cv::Set<1, -1, -1>, VDepth = cv::Set<0, 2, 5>, sizePolicy = cv::SizePolicy::NONE], file /home/.../color.hpp, line 259

If i left something out, let me know


回答1:


You must reshape "newvalue"

height, width = camera.texture.height, camera.texture.width

newvalue = np.frombuffer(camera.texture.pixels, np.uint8)
newvalue = newvalue.reshape(height, width, 4)
gray = cv2.cvtColor(newvalue, cv2.COLOR_RGBA2GRAY)


来源:https://stackoverflow.com/questions/58752956/convert-a-kivy-texture-to-opencv-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!