Detailed Explanation of the Code
Detailed Explanation of the Code
Importing Libraries:
python
Copy
import cv2
cv2: This is the OpenCV library, which is widely used for computer vision and image
processing tasks. OpenCV stands for Open Source Computer Vision Library.
python
Copy
img = cv2.imread("D:/Photos/Images/rk.jpg")
cv2.imread: This function reads an image from the specified file. The path should
be accurate to avoid errors. If the image is not found, img will be None.
python
Copy
if img is None:
print("Error: Image not found. Please check the file path.")
exit()
if img is None: This checks if the image was loaded successfully. If not, it prints
an error message and exits the program.
Converting to Grayscale:
python
Copy
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.cvtColor: This function converts the color space of an image. Here, it converts
the image from BGR (Blue, Green, Red) to Grayscale.
cv2.COLOR_BGR2GRAY: This is the flag that specifies the conversion from BGR to
Grayscale.
python
Copy
invert = cv2.bitwise_not(gray)
cv2.bitwise_not: This function inverts the bits of an image. Here, it creates a
negative of the grayscale image, turning dark areas light and light areas dark.
python
Copy
blur = cv2.GaussianBlur(invert, (111, 111), 0)
cv2.GaussianBlur: This function applies a Gaussian blur to the image, which helps
smooth out the details. The parameters are:
(111, 111): The kernel size, which determines the extent of the blur. Larger values
result in more blur.
python
Copy
invert_blur = cv2.bitwise_not(blur)
cv2.bitwise_not: Again, this function inverts the bits of the blurred image,
creating a negative of the blurred image.
python
Copy
sketch = cv2.divide(gray, invert_blur, scale=256)
cv2.divide: This function performs element-wise division of the grayscale image by
the inverted blurred image. The scale parameter (256) helps to maintain the
intensity values within a visible range, creating a pencil sketch effect.
python
Copy
cv2.imshow("sketch", sketch)
cv2.imshow: This function displays an image in a window. The first parameter is the
window name ("sketch"), and the second parameter is the image to display.
python
Copy
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0): This function waits indefinitely for a key press. Passing 0 means
it waits forever.
cv2.destroyAllWindows: This function closes all OpenCV windows. It's good practice
to include this to clean up after displaying the image.
Combining the grayscale image and the inverted blurred image to produce the sketch
effect.
Functions Used: