Swapnil
Swapnil

Reputation: 9

How to convert list of pixel into image using python

I want to change specific pixel value in whole image.I have converted image into List using img.getdata() function.now after processing i want to convert that list into image format.please suggest me if you know any way to do so.

import cv2
import numpy as np

from PIL import Image
img = Image.open('test.jpg','r')
pix=list(img.getdata())
for i in pix:
    if i ==(254,0,0):
        print("found",i)
        pi=np.array(pix)
        pi=Image.fromarray(pi)
        cv2.imshow("img",pi)

Error is


Traceback (most recent call last):
  File "C:\Python38\pixels.py", line 19, in <module>
    cv2.imshow("img",pi)
TypeError: Expected Ptr<cv::UMat> for argument 'mat'

i have tried some other way also but not able to see image.

Upvotes: 0

Views: 1507

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 208003

This should help:

#!/usr/bin/env python3

import numpy as np
import cv2

# Open an image
im = cv2.imread('image.png')

# Count RGB(254,0 ,0) pixels
sought = [254,0,0]
total  = np.count_nonzero(np.all(im==sought,axis=2))
print(f'Total before: {total}')

# Draw a rectangle 10x10 that colour
im[0:10,0:10] = sought

# Count pixels that colour
total  = np.count_nonzero(np.all(im==sought,axis=2))
print(f'Total after: {total}')

# Save
cv2.imwrite('result.png',im)

enter image description here

enter image description here

Sample Output

Total before: 0
Total after: 100

Upvotes: 2

Related Questions