How to read pixels from a specific video frame
Asked Answered
S

1

5

I am trying to change a pixel in a specific video frame using OpenCV in Python. My current code is:

import cv2
cap = cv2.VideoCapture("plane.avi")
cap.set(1, 2) #2- the second frame of my video
res, frame = cap.read()
cv2.imshow("video", frame)
while True:
    ch = 0xFF & cv2.waitKey(1)
    if ch == 27:
        break

I got the frame that I want but I don't know how to get and change it's pixels. Please suggest a method.

Snob answered 24/4, 2019 at 10:6 Comment(0)
M
8

As per your question, you are trying to read the second frame using cv2.seek(). The pixel values are stored in the variable frame. In order to change it, you can access individual pixel values.

Example :

cap.set(1, 2)
res, frame = cap.read() #frame has your pixel values

#Get frame height and width to access pixels
height, width, channels = frame.shape

#Accessing BGR pixel values    
for x in range(0, width) :
     for y in range(0, height) :
          print (frame[x,y,0]) #B Channel Value
          print (frame[x,y,1]) #G Channel Value
          print (frame[x,y,2]) #R Channel Value
Modular answered 24/4, 2019 at 10:22 Comment(2)
Thanks a lot, I got it now! if i change the B,G,R channels in this code like this : frame[1,1,0] = 255 frame[1,1,1] = 255 frame[1,1,2] = 255 I make the pixel white, yeah?Snob
Yes. Exactly. Glad you figured it out. Can you accept my answer and close the topic please?Modular

© 2022 - 2024 — McMap. All rights reserved.